@keyou007/agent-bot 0.1.27-alpha.0 → 0.1.27-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 +35 -0
- package/README.md +63 -7
- package/README.zh.md +62 -6
- package/SECURITY.md +18 -4
- package/assets/workspace-sessions.js +648 -0
- package/assets/workspace.css +160 -0
- package/assets/workspace.js +1795 -0
- package/config.example.yaml +3 -2
- package/dist/codex/CodexEventMapper.js +35 -0
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +50 -4
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/codex/TraeTaskNotification.js +44 -0
- package/dist/codex/TraeTaskNotification.js.map +1 -0
- package/dist/config/SettingsStore.js +1 -1
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +3 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/paths.js +3 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/feishu/CardRenderer.js +56 -12
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +2 -2
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +103 -16
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +61 -17
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +1 -1
- package/dist/local-files/GitDiffPreview.js +167 -0
- package/dist/local-files/GitDiffPreview.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +332 -30
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownFileLinks.js +5 -4
- package/dist/local-files/MarkdownFileLinks.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +138 -58
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WebPageTitle.js +85 -0
- package/dist/local-files/WebPageTitle.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +553 -0
- package/dist/local-files/WorkspaceFiles.js.map +1 -0
- package/dist/local-files/WorkspaceOrigin.js +38 -0
- package/dist/local-files/WorkspaceOrigin.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +19 -0
- package/dist/local-files/WorkspacePage.js.map +1 -0
- package/dist/local-files/WorkspaceSessions.js +689 -0
- package/dist/local-files/WorkspaceSessions.js.map +1 -0
- package/dist/presentation/TurnStateReducer.js +74 -13
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnActivity.js +41 -0
- package/dist/presentation/turnActivity.js.map +1 -0
- package/dist/presentation/turnStatus.js +11 -0
- package/dist/presentation/turnStatus.js.map +1 -1
- package/dist/presentation/visibleTurnActivities.js +4 -2
- package/dist/presentation/visibleTurnActivities.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +150 -14
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/types.js +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/state/InboundMessageStore.js +54 -0
- package/dist/state/InboundMessageStore.js.map +1 -0
- package/dist/state/StateStore.js +71 -1
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +4 -2
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/migrations.js +20 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -0
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/supervision/SafeRestartScheduler.js +33 -16
- package/dist/supervision/SafeRestartScheduler.js.map +1 -1
- package/dist/terminal/TerminalLinks.js +32 -0
- package/dist/terminal/TerminalLinks.js.map +1 -1
- package/dist/terminal/TerminalPage.js +75 -26
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +125 -56
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +14 -4
- package/docs/technical-reference.zh.md +15 -5
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +6 -2
- package/src/codex/CodexEventMapper.ts +39 -1
- package/src/codex/CodexRuntime.ts +54 -4
- package/src/codex/TraeTaskNotification.ts +49 -0
- package/src/config/SettingsStore.ts +1 -1
- package/src/config/loadConfig.ts +3 -2
- package/src/config/paths.ts +4 -0
- package/src/feishu/CardRenderer.ts +47 -13
- package/src/feishu/FeishuMessageClient.ts +2 -2
- package/src/feishu/FeishuTurnPresenter.ts +110 -20
- package/src/index.ts +62 -17
- package/src/local-files/DiagramPreview.ts +1 -1
- package/src/local-files/GitDiffPreview.ts +144 -0
- package/src/local-files/LocalFileViewerServer.ts +294 -31
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +159 -69
- package/src/local-files/WebPageTitle.ts +59 -0
- package/src/local-files/WorkspaceFiles.ts +468 -0
- package/src/local-files/WorkspaceOrigin.ts +31 -0
- package/src/local-files/WorkspacePage.ts +21 -0
- package/src/local-files/WorkspaceSessions.ts +587 -0
- package/src/presentation/TurnStateReducer.ts +76 -14
- package/src/presentation/turnActivity.ts +43 -0
- package/src/presentation/turnStatus.ts +14 -0
- package/src/presentation/turnViewTypes.ts +10 -1
- package/src/presentation/visibleTurnActivities.ts +4 -2
- package/src/proxy/ProxySessionController.ts +149 -13
- package/src/runtime/types.ts +17 -0
- package/src/state/InboundMessageStore.ts +72 -0
- package/src/state/StateStore.ts +80 -1
- package/src/state/TurnPreviewJournal.ts +4 -2
- package/src/state/migrations.ts +20 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -0
- package/src/supervision/SafeRestartScheduler.ts +42 -18
- package/src/terminal/TerminalLinks.ts +26 -0
- package/src/terminal/TerminalPage.ts +76 -26
- package/src/terminal/TerminalServer.ts +119 -48
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { TurnPreviewJournal } from "../state/TurnPreviewJournal.js";
|
|
2
|
-
import type
|
|
2
|
+
import { TASK_NOTIFICATION_ACTIVITY_PREFIX, type AgentEvent } from "../runtime/types.js";
|
|
3
3
|
import {
|
|
4
4
|
appendSteerMessage as appendSteerMessageToState,
|
|
5
5
|
createTurnViewState,
|
|
@@ -14,6 +14,7 @@ import { CardRenderer } from "./CardRenderer.js";
|
|
|
14
14
|
import { CardUpdateScheduler } from "./CardUpdateScheduler.js";
|
|
15
15
|
import { normalizeFeishuMarkdown, type LocalFileUrlResolver } from "./FeishuMarkdown.js";
|
|
16
16
|
import type { FeishuOutbound, MessageReplyTarget } from "./types.js";
|
|
17
|
+
import { isThreadContextKey } from "./contextKey.js";
|
|
17
18
|
import {
|
|
18
19
|
FINAL_RESPONSE_BRANDING_BLOCK,
|
|
19
20
|
} from "./FinalResponseBranding.js";
|
|
@@ -44,6 +45,8 @@ export interface TurnPresentationStore {
|
|
|
44
45
|
getTurnSnapshot(turnId: string): unknown;
|
|
45
46
|
getTurnRuntimeOrigin?(turnId: string): { agentName: string; remoteSessionId: string } | undefined;
|
|
46
47
|
getTurnContextKey?(turnId: string): string | undefined;
|
|
48
|
+
findLatestMessageIdForSession?(localSessionId: string, contextKey?: string): string | undefined;
|
|
49
|
+
findLatestMessageIdForContext?(contextKey: string): string | undefined;
|
|
47
50
|
saveTurnDelivery(turnId: string, patch: { progressMessageId?: string; lastCardHash?: string }): void;
|
|
48
51
|
saveFinalDeliveryProgress(turnId: string, messageIds: string[]): void;
|
|
49
52
|
markFinalDelivered(turnId: string, messageIds: string[]): void;
|
|
@@ -91,6 +94,7 @@ export class FeishuTurnPresenter {
|
|
|
91
94
|
private readonly pendingEntries = new Map<string, TurnEntry>();
|
|
92
95
|
private readonly renderer: CardRenderer;
|
|
93
96
|
private readonly dirty = new Map<string, { state: TurnViewState; contextKey?: string }>();
|
|
97
|
+
private readonly taskNotificationDeliveries = new Map<string, Promise<void>>();
|
|
94
98
|
private persistTimer?: NodeJS.Timeout;
|
|
95
99
|
|
|
96
100
|
constructor(
|
|
@@ -286,8 +290,9 @@ export class FeishuTurnPresenter {
|
|
|
286
290
|
): Promise<void> {
|
|
287
291
|
const activityId = `steer:${messageId ?? createId("message")}`;
|
|
288
292
|
let entry = this.entries.get(turnId);
|
|
293
|
+
const saved = entry?.state ?? this.store.getTurnSnapshot(turnId);
|
|
294
|
+
if (isTurnViewState(saved) && saved.taskNotificationCard) return;
|
|
289
295
|
if (!entry) {
|
|
290
|
-
const saved = this.store.getTurnSnapshot(turnId);
|
|
291
296
|
const contextKey = this.store.getTurnContextKey?.(turnId) ?? this.sessionContexts.get(sessionId);
|
|
292
297
|
if (!contextKey) return;
|
|
293
298
|
const initial = isTurnViewState(saved) && saved.sessionId === sessionId
|
|
@@ -426,13 +431,13 @@ export class FeishuTurnPresenter {
|
|
|
426
431
|
}
|
|
427
432
|
|
|
428
433
|
await entry.initializing;
|
|
429
|
-
if (!entry.scheduler) return;
|
|
434
|
+
if (!entry.scheduler && !(event.type === "turn_completed" && entry.state.taskNotificationCard)) return;
|
|
430
435
|
|
|
431
436
|
if (event.type === "turn_status_unknown" && entry.state.status === "unknown") {
|
|
432
437
|
if (this.pendingEntries.get(event.sessionId) === entry) this.pendingEntries.delete(event.sessionId);
|
|
433
438
|
entry.continuing = false;
|
|
434
439
|
this.stopElapsedUpdates(entry);
|
|
435
|
-
if (!entry.historySnapshot) await entry.scheduler
|
|
440
|
+
if (!entry.historySnapshot) await entry.scheduler?.flush(entry.state);
|
|
436
441
|
await this.syncThinkingCardReaction(entry);
|
|
437
442
|
return;
|
|
438
443
|
}
|
|
@@ -456,7 +461,7 @@ export class FeishuTurnPresenter {
|
|
|
456
461
|
}
|
|
457
462
|
|
|
458
463
|
if (event.type === "reasoning_delta" || event.type === "reasoning_completed") return;
|
|
459
|
-
if (!entry.historySnapshot) entry.scheduler
|
|
464
|
+
if (!entry.historySnapshot) entry.scheduler?.update(entry.state, eventPriority(event));
|
|
460
465
|
}
|
|
461
466
|
|
|
462
467
|
async showDetails(contextKey: string, turnId: string): Promise<void> {
|
|
@@ -521,8 +526,10 @@ export class FeishuTurnPresenter {
|
|
|
521
526
|
const delivery = this.store.getTurnDelivery(turnId);
|
|
522
527
|
if (delivery?.finalDelivered) return;
|
|
523
528
|
const snapshot = this.store.getTurnSnapshot(turnId);
|
|
524
|
-
if (!isTurnViewState(snapshot) || snapshot.status !== "completed"
|
|
525
|
-
|
|
529
|
+
if (!isTurnViewState(snapshot) || snapshot.status !== "completed") return;
|
|
530
|
+
const entry = snapshot.taskNotificationCard ? this.entries.get(turnId) : undefined;
|
|
531
|
+
if (entry) await entry.initializing;
|
|
532
|
+
await this.deliverFinal(contextKey, snapshot, entry?.scheduler);
|
|
526
533
|
}
|
|
527
534
|
|
|
528
535
|
async flushAll(): Promise<void> {
|
|
@@ -609,14 +616,18 @@ export class FeishuTurnPresenter {
|
|
|
609
616
|
if (messageId) {
|
|
610
617
|
await this.outbound.updateInteractiveCard(messageId, card);
|
|
611
618
|
} else {
|
|
612
|
-
|
|
619
|
+
const replyTarget = this.turnReplyTarget(entry.contextKey, sentState);
|
|
620
|
+
if (replyTarget && !this.outbound.replyInteractiveCard) throw new Error("当前消息通道不支持在话题中发送卡片。");
|
|
621
|
+
messageId = replyTarget && this.outbound.replyInteractiveCard
|
|
613
622
|
? await this.outbound.replyInteractiveCard(
|
|
614
623
|
entry.contextKey,
|
|
615
|
-
|
|
624
|
+
replyTarget,
|
|
616
625
|
card,
|
|
617
626
|
progressMessageKey(sentState.turnId),
|
|
618
627
|
)
|
|
619
|
-
:
|
|
628
|
+
: sentState.taskNotificationCard
|
|
629
|
+
? await this.outbound.sendInteractiveCard(entry.contextKey, card, progressMessageKey(sentState.turnId))
|
|
630
|
+
: await this.outbound.sendInteractiveCard(entry.contextKey, card);
|
|
620
631
|
}
|
|
621
632
|
entry.messageId = messageId;
|
|
622
633
|
if (!messageId) return;
|
|
@@ -634,11 +645,29 @@ export class FeishuTurnPresenter {
|
|
|
634
645
|
await this.syncThinkingCardReaction(entry);
|
|
635
646
|
}
|
|
636
647
|
|
|
648
|
+
private turnReplyTarget(contextKey: string, state: TurnViewState): MessageReplyTarget | undefined {
|
|
649
|
+
if (state.replyTarget) return state.replyTarget;
|
|
650
|
+
if (!isThreadContextKey(contextKey)) return undefined;
|
|
651
|
+
const messageId = this.store.findLatestMessageIdForSession?.(state.sessionId, contextKey)
|
|
652
|
+
?? this.store.findLatestMessageIdForContext?.(contextKey);
|
|
653
|
+
if (!messageId) throw new Error("无法确定当前话题的回复位置,未向群正文发送。");
|
|
654
|
+
return { messageId, replyInThread: true };
|
|
655
|
+
}
|
|
656
|
+
|
|
637
657
|
private renderTurn(state: TurnViewState): Record<string, unknown> {
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
this.
|
|
641
|
-
|
|
658
|
+
const previewUrl = this.turnPreviewUrl(state);
|
|
659
|
+
if (state.taskNotificationCard) {
|
|
660
|
+
const [answer, ...remaining] = this.taskNotificationAnswer(state);
|
|
661
|
+
return this.renderer.renderTaskNotification(state, previewUrl, answer, remaining.length > 0);
|
|
662
|
+
}
|
|
663
|
+
return this.renderer.renderTurn(normalizeTurnCardMarkdown(state, this.options.localFileUrl), previewUrl);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
private taskNotificationAnswer(state: TurnViewState): string[] {
|
|
667
|
+
const answer = state.status === "completed" && state.finalResponse?.trim();
|
|
668
|
+
if (!answer) return [];
|
|
669
|
+
return splitMarkdown(normalizeFeishuMarkdown(answer, state.projectCwd, this.options.localFileUrl),
|
|
670
|
+
this.options.finalChunkLength ?? 4_000, MAX_FINAL_TABLES_PER_CARD);
|
|
642
671
|
}
|
|
643
672
|
|
|
644
673
|
private renderTurnDetails(state: TurnViewState): Record<string, unknown> {
|
|
@@ -704,6 +733,13 @@ export class FeishuTurnPresenter {
|
|
|
704
733
|
}
|
|
705
734
|
|
|
706
735
|
private async finalize(entry: TurnEntry, state: TurnViewState): Promise<void> {
|
|
736
|
+
if (state.status === "completed" && state.taskNotificationCard) {
|
|
737
|
+
if (entry.historySnapshot) entry.scheduler?.invalidateRenderedCard();
|
|
738
|
+
entry.historySnapshot = undefined;
|
|
739
|
+
await this.deliverFinal(entry.contextKey, state, entry.scheduler);
|
|
740
|
+
await this.syncThinkingCardReaction(entry);
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
707
743
|
let terminalCardError: unknown;
|
|
708
744
|
if (!entry.historySnapshot) {
|
|
709
745
|
try {
|
|
@@ -757,21 +793,72 @@ export class FeishuTurnPresenter {
|
|
|
757
793
|
}
|
|
758
794
|
}
|
|
759
795
|
|
|
760
|
-
private async deliverFinal(
|
|
796
|
+
private async deliverFinal(
|
|
797
|
+
contextKey: string,
|
|
798
|
+
state: TurnViewState,
|
|
799
|
+
scheduler?: CardUpdateScheduler<TurnViewState>,
|
|
800
|
+
): Promise<void> {
|
|
761
801
|
const delivery = this.store.getTurnDelivery(state.turnId);
|
|
762
|
-
if (delivery?.finalDelivered
|
|
763
|
-
|
|
802
|
+
if (delivery?.finalDelivered) return;
|
|
803
|
+
if (state.taskNotificationCard) {
|
|
804
|
+
let pending = this.taskNotificationDeliveries.get(state.turnId);
|
|
805
|
+
if (!pending) {
|
|
806
|
+
pending = this.deliverTaskNotification(contextKey, state, delivery, scheduler)
|
|
807
|
+
.finally(() => this.taskNotificationDeliveries.delete(state.turnId));
|
|
808
|
+
this.taskNotificationDeliveries.set(state.turnId, pending);
|
|
809
|
+
}
|
|
810
|
+
await pending;
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
if (!state.finalResponse) return;
|
|
764
814
|
const chunks = brandedFinalChunks(
|
|
765
815
|
normalizeFeishuMarkdown(state.finalResponse, state.projectCwd, this.options.localFileUrl),
|
|
766
|
-
finalChunkLength,
|
|
816
|
+
this.options.finalChunkLength ?? 4_000,
|
|
767
817
|
);
|
|
818
|
+
await this.deliverFinalChunks(contextKey, state, chunks, delivery);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
private async deliverTaskNotification(
|
|
822
|
+
contextKey: string,
|
|
823
|
+
state: TurnViewState,
|
|
824
|
+
delivery?: TurnDeliveryRecord,
|
|
825
|
+
scheduler?: CardUpdateScheduler<TurnViewState>,
|
|
826
|
+
): Promise<void> {
|
|
827
|
+
if (scheduler) {
|
|
828
|
+
await scheduler.flush(state);
|
|
829
|
+
} else {
|
|
830
|
+
const card = this.renderTurn(state);
|
|
831
|
+
if (delivery?.progressMessageId) {
|
|
832
|
+
await this.outbound.updateInteractiveCard(delivery.progressMessageId, card);
|
|
833
|
+
} else {
|
|
834
|
+
const key = progressMessageKey(state.turnId);
|
|
835
|
+
const replyTarget = this.turnReplyTarget(contextKey, state);
|
|
836
|
+
if (replyTarget && !this.outbound.replyInteractiveCard) throw new Error("当前消息通道不支持在话题中发送卡片。");
|
|
837
|
+
const messageId = replyTarget && this.outbound.replyInteractiveCard
|
|
838
|
+
? await this.outbound.replyInteractiveCard(contextKey, replyTarget, card, key)
|
|
839
|
+
: await this.outbound.sendInteractiveCard(contextKey, card, key);
|
|
840
|
+
if (!messageId) throw new Error("后台任务通知卡片未返回消息 ID。");
|
|
841
|
+
this.store.saveTurnDelivery(state.turnId, { progressMessageId: messageId });
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
// The card serves as the final delivery. Only spill oversized replies when Preview is unavailable.
|
|
845
|
+
const remaining = this.turnPreviewUrl(state) ? [] : this.taskNotificationAnswer(state).slice(1);
|
|
846
|
+
await this.deliverFinalChunks(contextKey, state, remaining, delivery);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
private async deliverFinalChunks(
|
|
850
|
+
contextKey: string,
|
|
851
|
+
state: TurnViewState,
|
|
852
|
+
chunks: string[],
|
|
853
|
+
delivery?: TurnDeliveryRecord,
|
|
854
|
+
): Promise<void> {
|
|
768
855
|
const messageIds = [...(delivery?.finalMessageIds ?? [])];
|
|
769
856
|
for (let index = messageIds.length; index < chunks.length; index += 1) {
|
|
770
857
|
const chunk = chunks[index];
|
|
771
858
|
if (chunk === undefined) continue;
|
|
772
859
|
const messageId = await this.sendFinalChunk(
|
|
773
860
|
contextKey,
|
|
774
|
-
|
|
861
|
+
this.turnReplyTarget(contextKey, state),
|
|
775
862
|
chunk,
|
|
776
863
|
finalMessageKey(state.turnId, index),
|
|
777
864
|
);
|
|
@@ -787,6 +874,7 @@ export class FeishuTurnPresenter {
|
|
|
787
874
|
chunk: string,
|
|
788
875
|
idempotencyKey: string,
|
|
789
876
|
): Promise<string | undefined> {
|
|
877
|
+
if (replyTarget && !this.outbound.replyMarkdown) throw new Error("当前消息通道不支持在话题中发送回答。");
|
|
790
878
|
const backoffs = this.options.finalRetryBackoffMs ?? [2_000, 4_000, 8_000];
|
|
791
879
|
for (let attempt = 0; ; attempt += 1) {
|
|
792
880
|
try {
|
|
@@ -863,11 +951,13 @@ function brandedFinalChunks(response: string, maxLength: number): string[] {
|
|
|
863
951
|
function eventPriority(event: AgentEvent): "normal" | "critical" {
|
|
864
952
|
if (
|
|
865
953
|
event.type === "turn_started"
|
|
954
|
+
|| event.type === "model_queue_updated"
|
|
866
955
|
|| event.type === "approval_requested"
|
|
867
956
|
|| event.type === "approval_resolved"
|
|
868
957
|
|| event.type === "tool_started"
|
|
869
958
|
|| event.type === "context_compaction"
|
|
870
|
-
|| (event.type === "progress" && event.severity === "warning"
|
|
959
|
+
|| (event.type === "progress" && (event.severity === "warning"
|
|
960
|
+
|| event.activityId?.startsWith(TASK_NOTIFICATION_ACTIVITY_PREFIX)))
|
|
871
961
|
) {
|
|
872
962
|
return "critical";
|
|
873
963
|
}
|
package/src/index.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
agentBotHome,
|
|
16
16
|
defaultConfigPath,
|
|
17
17
|
defaultDotEnvPath,
|
|
18
|
+
inboundImageDirectory,
|
|
18
19
|
resolveUserPath,
|
|
19
20
|
} from "./config/paths.js";
|
|
20
21
|
import { ConsoleConnector } from "./console/ConsoleConnector.js";
|
|
@@ -49,11 +50,13 @@ import {
|
|
|
49
50
|
restartGroupContextKeysFromEnvironment,
|
|
50
51
|
restartNotificationTargetsFromEnvironment,
|
|
51
52
|
} from "./supervision/replacementSupervisor.js";
|
|
52
|
-
import { SafeRestartScheduler } from "./supervision/SafeRestartScheduler.js";
|
|
53
|
+
import { commitRestartHandoff, SafeRestartScheduler } from "./supervision/SafeRestartScheduler.js";
|
|
53
54
|
import type { RestartNotificationTarget } from "./supervision/SafeRestartScheduler.js";
|
|
54
55
|
import { SafeRestartNotifier } from "./supervision/SafeRestartNotifier.js";
|
|
55
56
|
import { privateRestartNotificationTarget } from "./supervision/restartNotificationTarget.js";
|
|
56
57
|
import { LocalFileViewerServer } from "./local-files/LocalFileViewerServer.js";
|
|
58
|
+
import { WorkspaceSessions } from "./local-files/WorkspaceSessions.js";
|
|
59
|
+
import { WorkspaceError } from "./local-files/WorkspaceFiles.js";
|
|
57
60
|
import {
|
|
58
61
|
nodeDiagnosticReportArguments,
|
|
59
62
|
prepareCrashReportDirectory,
|
|
@@ -84,6 +87,7 @@ const transport = consoleOnly ? "console" : requireServerFeishuTransport(config.
|
|
|
84
87
|
const logger = createLogger(config);
|
|
85
88
|
const store = new StateStore(config.storage.sqlitePath, (error) => logger.error({ error }, "Failed to persist Turn preview journal."));
|
|
86
89
|
let localFileViewer: LocalFileViewerServer | undefined;
|
|
90
|
+
let workspaceSessions: WorkspaceSessions | undefined;
|
|
87
91
|
let terminalServer: TerminalServer | undefined;
|
|
88
92
|
const shellCommandJobs = new ShellCommandJobManager(path.join(path.dirname(config.storage.sqlitePath), "command-jobs"));
|
|
89
93
|
let loadTurnDetails: ((turnId: string) => Promise<unknown>) | undefined;
|
|
@@ -95,6 +99,10 @@ if (config.fileViewer.enabled) {
|
|
|
95
99
|
stateDirectory: path.join(path.dirname(config.storage.sqlitePath), "file-viewer"),
|
|
96
100
|
previewJournal: store.previews,
|
|
97
101
|
getTurnSnapshot: (turnId) => store.getTurnSnapshot(turnId),
|
|
102
|
+
createWorkspaceTerminalUrl: (root, instance, request) => {
|
|
103
|
+
if (!terminalServer) throw new WorkspaceError("网页终端服务未启用,请确认终端已开启并配置飞书所有者。", 503);
|
|
104
|
+
return terminalServer.createWorkspaceUrl(root, instance, request);
|
|
105
|
+
},
|
|
98
106
|
loadTurnSnapshot: (turnId) => loadTurnDetails?.(turnId) ?? Promise.resolve(store.getTurnSnapshot(turnId)),
|
|
99
107
|
});
|
|
100
108
|
try {
|
|
@@ -170,6 +178,7 @@ if (consoleOutbound) {
|
|
|
170
178
|
|
|
171
179
|
if (routes.length === 0) throw new Error("Neither Feishu nor console input is enabled.");
|
|
172
180
|
const outbound = new OutboundRouter(routes);
|
|
181
|
+
let controller: ProxySessionController;
|
|
173
182
|
let shuttingDown = false;
|
|
174
183
|
let restartRequested = false;
|
|
175
184
|
let pendingSelfUpdatePlanPath: string | undefined;
|
|
@@ -177,8 +186,8 @@ let preparingSelfUpdate = false;
|
|
|
177
186
|
const safeRestart = new SafeRestartScheduler({
|
|
178
187
|
readActivity: () => serverActivity(),
|
|
179
188
|
onReady: (reason, notificationTargets) => pendingSelfUpdatePlanPath
|
|
180
|
-
? initiateSelfUpdate(reason, notificationTargets)
|
|
181
|
-
: initiateRestart(reason, notificationTargets),
|
|
189
|
+
? initiateSelfUpdate(reason, notificationTargets, safeRestart.forcing)
|
|
190
|
+
: initiateRestart(reason, notificationTargets, safeRestart.forcing),
|
|
182
191
|
onStatus: (status) => safeRestartNotifier?.update(status),
|
|
183
192
|
onStatusError: (error) => logger.warn({ error }, "Failed to publish safe restart status."),
|
|
184
193
|
});
|
|
@@ -241,11 +250,14 @@ async function prepareAndScheduleUpdate(version: string, target: RestartNotifica
|
|
|
241
250
|
}
|
|
242
251
|
}
|
|
243
252
|
|
|
253
|
+
const browserPassword = () => config.terminal?.password ?? DEFAULT_TERMINAL_PASSWORD;
|
|
254
|
+
|
|
244
255
|
if (feishuOutbound && localFileViewer && config.terminal?.enabled !== false) {
|
|
245
256
|
const server = new TerminalServer({
|
|
246
257
|
stateDirectory: path.join(path.dirname(config.storage.sqlitePath), "terminal"),
|
|
247
258
|
ownerId: () => config.feishu.userOpenId,
|
|
248
|
-
password:
|
|
259
|
+
password: browserPassword,
|
|
260
|
+
workspaceAccess: (request, origin) => workspaceSessions?.terminalAccess(request, origin),
|
|
249
261
|
canStart: () => !shuttingDown && !restartRequested && !safeRestart.scheduled && !safeRestart.restarting,
|
|
250
262
|
readJob: (jobId) => shellCommandJobs.readJob(jobId),
|
|
251
263
|
requestApproval: (authorization) => sendTerminalAuthorization(feishuOutbound, authorization),
|
|
@@ -255,7 +267,7 @@ if (feishuOutbound && localFileViewer && config.terminal?.enabled !== false) {
|
|
|
255
267
|
try {
|
|
256
268
|
const publicBaseUrl = await server.start(localFileViewer);
|
|
257
269
|
terminalServer = server;
|
|
258
|
-
logger.info({ publicBaseUrl }, "Interactive terminal service started
|
|
270
|
+
logger.info({ publicBaseUrl }, "Interactive terminal service started.");
|
|
259
271
|
} catch (error) {
|
|
260
272
|
await server.close();
|
|
261
273
|
logger.warn({ error }, "Terminal service unavailable; command cards remain usable.");
|
|
@@ -265,10 +277,11 @@ if (feishuOutbound && localFileViewer && config.terminal?.enabled !== false) {
|
|
|
265
277
|
function serverActivity() {
|
|
266
278
|
const activity = store.getServerActivityState();
|
|
267
279
|
const terminalBlockers = terminalServer?.listActiveTerminals() ?? [];
|
|
268
|
-
|
|
280
|
+
const pendingInboundMessages = (controller?.pendingInboundMessages ?? 0) + (workspaceSessions?.preparingActions ?? 0);
|
|
281
|
+
return { ...activity, pendingInboundMessages, activeTerminals: terminalBlockers.length, terminalBlockers };
|
|
269
282
|
}
|
|
270
283
|
|
|
271
|
-
|
|
284
|
+
controller = new ProxySessionController(config, store, runtimes, outbound, logger, {
|
|
272
285
|
settings: new SettingsStore(activeConfigPath, config),
|
|
273
286
|
canStartScheduledTasks: () => serverReady && !shuttingDown && !restartRequested && !safeRestart.scheduled,
|
|
274
287
|
supervised,
|
|
@@ -315,6 +328,17 @@ const controller = new ProxySessionController(config, store, runtimes, outbound,
|
|
|
315
328
|
},
|
|
316
329
|
}, undefined, undefined, shellCommandJobs);
|
|
317
330
|
loadTurnDetails = (turnId) => controller.loadTurnDetails(turnId);
|
|
331
|
+
if (localFileViewer && feishuOutbound) {
|
|
332
|
+
workspaceSessions = new WorkspaceSessions(localFileViewer, {
|
|
333
|
+
store, controller, logger,
|
|
334
|
+
inboundImageDirectory: inboundImageDirectory(config.storage.sqlitePath),
|
|
335
|
+
owner: () => config.feishu.userOpenId,
|
|
336
|
+
password: browserPassword,
|
|
337
|
+
isAppServer: (name) => config.agents[name]?.kind === "app-server",
|
|
338
|
+
canSubmit: () => serverReady && !shuttingDown && !restartRequested && !safeRestart.scheduled,
|
|
339
|
+
});
|
|
340
|
+
localFileViewer.enableWorkspaceApp(workspaceSessions.start());
|
|
341
|
+
}
|
|
318
342
|
|
|
319
343
|
if (feishuOutbound) {
|
|
320
344
|
feishuConnector = new FeishuConnector(
|
|
@@ -428,14 +452,15 @@ async function requestRestart(
|
|
|
428
452
|
async function initiateRestart(
|
|
429
453
|
reason: string,
|
|
430
454
|
notificationTargets: RestartNotificationTarget[] = [],
|
|
431
|
-
|
|
455
|
+
force = true,
|
|
456
|
+
): Promise<boolean> {
|
|
432
457
|
if (restartRequested) {
|
|
433
458
|
await sendRestartTexts(notificationTargets, "Agent Bot 已在重启中,请稍候。");
|
|
434
|
-
return;
|
|
459
|
+
return false;
|
|
435
460
|
}
|
|
436
461
|
restartRequested = true;
|
|
437
|
-
|
|
438
|
-
|
|
462
|
+
const activity = serverActivity();
|
|
463
|
+
if (force) safeRestart.cancel();
|
|
439
464
|
await safeRestartNotifier?.flush();
|
|
440
465
|
const allNotificationTargets = mergeRestartNotificationTargets(
|
|
441
466
|
notificationTargets,
|
|
@@ -445,24 +470,29 @@ async function initiateRestart(
|
|
|
445
470
|
allNotificationTargets,
|
|
446
471
|
"Agent Bot 正在重启,恢复在线后会发送启动状态通知。",
|
|
447
472
|
);
|
|
473
|
+
if (!commitRestart(force, activity.latestInboundAt)) return false;
|
|
474
|
+
pendingSelfUpdatePlanPath = undefined;
|
|
448
475
|
setTimeout(() => void shutdown(
|
|
449
476
|
supervised ? STOP_EXIT_CODE : 0,
|
|
450
477
|
reason,
|
|
451
478
|
allNotificationTargets,
|
|
452
479
|
), 100);
|
|
480
|
+
return true;
|
|
453
481
|
}
|
|
454
482
|
|
|
455
483
|
async function initiateSelfUpdate(
|
|
456
484
|
reason: string,
|
|
457
485
|
notificationTargets: RestartNotificationTarget[] = [],
|
|
458
|
-
|
|
486
|
+
force = true,
|
|
487
|
+
): Promise<boolean> {
|
|
459
488
|
if (restartRequested) {
|
|
460
489
|
await sendRestartTexts(notificationTargets, "Agent Bot 已在重启或更新中,请稍候。");
|
|
461
|
-
return;
|
|
490
|
+
return false;
|
|
462
491
|
}
|
|
463
492
|
const planPath = pendingSelfUpdatePlanPath;
|
|
464
|
-
if (!planPath) return;
|
|
493
|
+
if (!planPath) return false;
|
|
465
494
|
restartRequested = true;
|
|
495
|
+
const activity = serverActivity();
|
|
466
496
|
await safeRestartNotifier?.flush();
|
|
467
497
|
const allNotificationTargets = mergeRestartNotificationTargets(
|
|
468
498
|
notificationTargets,
|
|
@@ -476,6 +506,8 @@ async function initiateSelfUpdate(
|
|
|
476
506
|
if (environmentRefresh.error) {
|
|
477
507
|
logger.warn({ error: environmentRefresh.error }, "Failed to refresh the environment for Agent Bot update.");
|
|
478
508
|
}
|
|
509
|
+
// No awaits between this last check and stopping message dispatch.
|
|
510
|
+
if (!commitRestart(force, activity.latestInboundAt)) return false;
|
|
479
511
|
try {
|
|
480
512
|
assertSelfUpdatePlanPath(planPath, agentBotHome());
|
|
481
513
|
launchSelfUpdateRunner(planPath, {
|
|
@@ -488,6 +520,8 @@ async function initiateSelfUpdate(
|
|
|
488
520
|
});
|
|
489
521
|
} catch (error) {
|
|
490
522
|
restartRequested = false;
|
|
523
|
+
controller.resumeInboundMessages();
|
|
524
|
+
safeRestart.cancel();
|
|
491
525
|
releaseSelfUpdatePlan(planPath);
|
|
492
526
|
pendingSelfUpdatePlanPath = undefined;
|
|
493
527
|
logger.error({ error, planPath }, "Failed to launch Agent Bot self-update; keeping the current service online.");
|
|
@@ -495,10 +529,20 @@ async function initiateSelfUpdate(
|
|
|
495
529
|
allNotificationTargets,
|
|
496
530
|
`Agent Bot 更新未启动,当前服务保持在线:${error instanceof Error ? error.message : String(error)}`,
|
|
497
531
|
);
|
|
498
|
-
return;
|
|
532
|
+
return false;
|
|
499
533
|
}
|
|
500
534
|
pendingSelfUpdatePlanPath = undefined;
|
|
501
535
|
setTimeout(() => void shutdown(STOP_EXIT_CODE), 100);
|
|
536
|
+
return true;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function commitRestart(force: boolean, latestInboundAt: string | undefined): boolean {
|
|
540
|
+
const activity = serverActivity();
|
|
541
|
+
if (!commitRestartHandoff(activity, latestInboundAt, () => controller.pauseInboundMessages(), force)) {
|
|
542
|
+
restartRequested = false;
|
|
543
|
+
return false;
|
|
544
|
+
}
|
|
545
|
+
return true;
|
|
502
546
|
}
|
|
503
547
|
|
|
504
548
|
async function handleControlRequest(request: ControlRequest): Promise<ControlResponse> {
|
|
@@ -681,6 +725,7 @@ async function shutdown(
|
|
|
681
725
|
): Promise<void> {
|
|
682
726
|
if (shuttingDown) return;
|
|
683
727
|
shuttingDown = true;
|
|
728
|
+
controller.pauseInboundMessages();
|
|
684
729
|
await taskScheduler?.stop();
|
|
685
730
|
await dailyUpdateMonitor?.stop();
|
|
686
731
|
if (pendingSelfUpdatePlanPath) {
|
|
@@ -769,8 +814,8 @@ function inferServerRestartTarget(notificationSessionId?: string): RestartNotifi
|
|
|
769
814
|
return privateRestartNotificationTarget(config.feishu.userOpenId);
|
|
770
815
|
}
|
|
771
816
|
|
|
772
|
-
function isServerIdle(activity: { runningSessions: number; pendingFinalDeliveries: number; activeTerminals?: number }): boolean {
|
|
773
|
-
return activity.runningSessions === 0 && activity.pendingFinalDeliveries === 0 && !activity.activeTerminals;
|
|
817
|
+
function isServerIdle(activity: { runningSessions: number; pendingFinalDeliveries: number; activeTerminals?: number; pendingInboundMessages?: number }): boolean {
|
|
818
|
+
return activity.runningSessions === 0 && activity.pendingFinalDeliveries === 0 && !activity.activeTerminals && !activity.pendingInboundMessages;
|
|
774
819
|
}
|
|
775
820
|
|
|
776
821
|
function restartNotificationTargetForSession(
|
|
@@ -162,7 +162,7 @@ export const DIAGRAM_PREVIEW_CLIENT_SCRIPT = String.raw`(() => {
|
|
|
162
162
|
schedule(block, state);
|
|
163
163
|
});
|
|
164
164
|
});
|
|
165
|
-
} else if (state.source === source) { return; }
|
|
165
|
+
} else if (state.source === source && (state.mode !== "preview" || state.rendered === source || state.error)) { return; }
|
|
166
166
|
else { state.source = source; state.error = false; }
|
|
167
167
|
show(block, state);
|
|
168
168
|
schedule(block, state);
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
|
|
6
|
+
const runFile = promisify(execFile);
|
|
7
|
+
const MAX_DIFF_BYTES = 1024 * 1024;
|
|
8
|
+
const MAX_DIFF_LINES = 10_000;
|
|
9
|
+
const MAX_MERGED_LINES = 20_000;
|
|
10
|
+
|
|
11
|
+
export async function readGitFileDiff(filePath: string): Promise<string | undefined> {
|
|
12
|
+
try {
|
|
13
|
+
const stat = fs.statSync(filePath, { throwIfNoEntry: false });
|
|
14
|
+
if (stat && (!stat.isFile() || stat.size > 2 * 1024 * 1024)) return undefined;
|
|
15
|
+
let cwd = path.dirname(filePath);
|
|
16
|
+
while (!fs.existsSync(cwd)) {
|
|
17
|
+
const parent = path.dirname(cwd);
|
|
18
|
+
if (parent === cwd) return undefined;
|
|
19
|
+
cwd = parent;
|
|
20
|
+
}
|
|
21
|
+
const signal = AbortSignal.timeout(4000);
|
|
22
|
+
const env: NodeJS.ProcessEnv = { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" };
|
|
23
|
+
for (const name of Object.keys(env)) {
|
|
24
|
+
if (/^GIT_(?:DIR|WORK_TREE|COMMON_DIR|INDEX_FILE|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES|CONFIG.*)$/u.test(name)) delete env[name];
|
|
25
|
+
}
|
|
26
|
+
const args = ["--no-pager", "--literal-pathspecs", "-c", "core.fsmonitor=false", "-c", "core.quotepath=false"];
|
|
27
|
+
const git = async (command: string[]): Promise<{ stdout: string; code: number }> => {
|
|
28
|
+
try {
|
|
29
|
+
const result = await runFile("git", [...args, ...command], { cwd, env, signal, windowsHide: true, maxBuffer: MAX_DIFF_BYTES, encoding: "buffer" });
|
|
30
|
+
return { stdout: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(result.stdout), code: 0 };
|
|
31
|
+
} catch (error) {
|
|
32
|
+
const failure = error as { code?: unknown; stdout?: Buffer };
|
|
33
|
+
if (typeof failure.code === "number") return { stdout: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(failure.stdout), code: failure.code };
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const head = await git(["rev-parse", "--verify", "--quiet", "HEAD"]);
|
|
38
|
+
if (head.code !== 0) return undefined;
|
|
39
|
+
// Diff must not execute repository clean/process filters or filesystem monitors.
|
|
40
|
+
const filters = await git(["config", "--null", "--name-only", "--get-regexp", "^filter\\..*\\.(clean|process|required)$"]);
|
|
41
|
+
if (filters.code !== 0 && filters.code !== 1) return undefined;
|
|
42
|
+
const names = filters.stdout.split("\0").filter(Boolean);
|
|
43
|
+
if (names.length > 128 || names.some((name) => !/^filter\.[^\r\n]+\.(?:clean|process|required)$/u.test(name))) return undefined;
|
|
44
|
+
for (const name of names) args.push("-c", `${name}=${name.endsWith(".required") ? "false" : ""}`);
|
|
45
|
+
const relative = path.relative(cwd, filePath).split(path.sep).join("/");
|
|
46
|
+
const previous = await git(["ls-tree", "-z", "HEAD", "--", relative]);
|
|
47
|
+
if (previous.code !== 0 || !previous.stdout) return undefined;
|
|
48
|
+
const options = ["diff", "--no-ext-diff", "--no-textconv", "--no-color", "--no-renames", "--unified=3"];
|
|
49
|
+
const result = await git([...options, "HEAD", "--", relative]);
|
|
50
|
+
if (result.code > 1 || !result.stdout.startsWith("diff --git ")) return undefined;
|
|
51
|
+
if (result.stdout.includes("\0") || /^Binary files /mu.test(result.stdout) || result.stdout.split("\n").length > MAX_DIFF_LINES) return undefined;
|
|
52
|
+
return result.stdout;
|
|
53
|
+
} catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type DiffLine = { kind: "context" | "addition" | "deletion"; text: string; oldNumber?: number; newNumber?: number };
|
|
59
|
+
|
|
60
|
+
export function renderGitFileDiff(diff: string, currentText: string, highlight?: (text: string) => string[]): string | undefined {
|
|
61
|
+
const source = splitLines(currentText.replace(/^\uFEFF/u, ""));
|
|
62
|
+
if (source.length > MAX_MERGED_LINES) return undefined;
|
|
63
|
+
const lines = splitLines(diff);
|
|
64
|
+
if (!lines[0]?.startsWith("diff --git ")) return undefined;
|
|
65
|
+
const rows: DiffLine[] = [];
|
|
66
|
+
let oldLine = 1;
|
|
67
|
+
let newLine = 1;
|
|
68
|
+
let inHunks = false;
|
|
69
|
+
const append = (kind: DiffLine["kind"], text: string): boolean => {
|
|
70
|
+
if (kind !== "deletion") {
|
|
71
|
+
if (newLine === 1) text = text.replace(/^\uFEFF/u, "");
|
|
72
|
+
if (source[newLine - 1] !== text) return false;
|
|
73
|
+
}
|
|
74
|
+
rows.push({ kind, text, ...(kind !== "addition" ? { oldNumber: oldLine++ } : {}),
|
|
75
|
+
...(kind !== "deletion" ? { newNumber: newLine++ } : {}) });
|
|
76
|
+
return rows.length <= MAX_MERGED_LINES;
|
|
77
|
+
};
|
|
78
|
+
// Git identifies edits; fill the gaps from the complete current file, checking hunk coordinates and text.
|
|
79
|
+
for (let index = 1; index < lines.length; index += 1) {
|
|
80
|
+
const line = lines[index]!;
|
|
81
|
+
const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/u.exec(line);
|
|
82
|
+
if (!hunk) {
|
|
83
|
+
if (line === "\") continue;
|
|
84
|
+
if (inHunks || line.startsWith("@@") || line.startsWith("diff --git ") || line === "GIT binary patch") return undefined;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
inHunks = true;
|
|
88
|
+
let oldRemaining = Number(hunk[2] ?? 1);
|
|
89
|
+
let newRemaining = Number(hunk[4] ?? 1);
|
|
90
|
+
const oldStart = Number(hunk[1]) + (oldRemaining === 0 ? 1 : 0);
|
|
91
|
+
const newStart = Number(hunk[3]) + (newRemaining === 0 ? 1 : 0);
|
|
92
|
+
if (![oldStart, newStart, oldRemaining, newRemaining].every(Number.isSafeInteger)
|
|
93
|
+
|| oldStart < oldLine || newStart < newLine || newStart > source.length + 1
|
|
94
|
+
|| oldStart - oldLine !== newStart - newLine) return undefined;
|
|
95
|
+
while (newLine < newStart) if (!append("context", source[newLine - 1]!)) return undefined;
|
|
96
|
+
while (oldRemaining > 0 || newRemaining > 0) {
|
|
97
|
+
const entry = lines[++index];
|
|
98
|
+
if (entry === "\") continue;
|
|
99
|
+
if (entry === undefined) return undefined;
|
|
100
|
+
const marker = entry[0];
|
|
101
|
+
if (marker !== " " && marker !== "+" && marker !== "-") return undefined;
|
|
102
|
+
if (marker !== "+" && --oldRemaining < 0) return undefined;
|
|
103
|
+
if (marker !== "-" && --newRemaining < 0) return undefined;
|
|
104
|
+
if (!append(marker === "+" ? "addition" : marker === "-" ? "deletion" : "context", entry.slice(1))) return undefined;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
while (newLine <= source.length) if (!append("context", source[newLine - 1]!)) return undefined;
|
|
108
|
+
const before = highlight?.(rows.filter((row) => row.kind !== "addition").map((row) => row.text).join("\n"));
|
|
109
|
+
const after = highlight?.(source.join("\n"));
|
|
110
|
+
const content = rows.map((row) => {
|
|
111
|
+
const id = row.newNumber !== undefined ? `L${row.newNumber}` : `D${row.oldNumber}`;
|
|
112
|
+
const oldNumber = `<span class="diff-number" aria-hidden="true">${row.oldNumber ?? ""}</span>`;
|
|
113
|
+
const newNumber = row.newNumber !== undefined
|
|
114
|
+
? `<a class="diff-number" href="#${id}" aria-label="Line ${row.newNumber}">${row.newNumber}</a>`
|
|
115
|
+
: '<span class="diff-number" aria-hidden="true"></span>';
|
|
116
|
+
const marker = row.kind === "addition" ? "+" : row.kind === "deletion" ? "-" : " ";
|
|
117
|
+
const text = row.kind === "deletion" ? before?.[row.oldNumber! - 1] : after?.[row.newNumber! - 1];
|
|
118
|
+
return `<span class="line diff-${row.kind}" id="${id}">${oldNumber}${newNumber}<span class="diff-marker" aria-hidden="true">${marker}</span><span class="diff-text">${text ?? escapeHtml(row.text)}</span></span>`;
|
|
119
|
+
}).join("");
|
|
120
|
+
return `<pre class="code git-diff" aria-label="Git diff"><code>${content}</code></pre>`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function splitLines(value: string): string[] {
|
|
124
|
+
return value === "" ? [] : value.replace(/\r\n?/gu, "\n").replace(/\n$/u, "").split("\n");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function escapeHtml(value: string): string {
|
|
128
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const GIT_DIFF_PREVIEW_CSS = `
|
|
132
|
+
.git-diff .line { display:flex; width:max-content; min-width:100%; padding-right:16px; }
|
|
133
|
+
.git-diff .diff-number { display:inline-block; flex:0 0 4.5em; width:4.5em; padding:0 10px; text-align:right; color:#6e7781; border-right:1px solid #d8dee4; text-decoration:none; user-select:none; }
|
|
134
|
+
.git-diff .diff-marker { flex:0 0 2em; width:2em; text-align:center; user-select:none; }
|
|
135
|
+
.git-diff .diff-text { white-space:pre; }
|
|
136
|
+
.git-diff .diff-addition { background:#dafbe1; color:#116329; }
|
|
137
|
+
.git-diff .diff-deletion { background:#ffebe9; color:#a40e26; }
|
|
138
|
+
@media (max-width:640px) { .git-diff .diff-number { flex-basis:3.5em; width:3.5em; padding:0 6px; } }
|
|
139
|
+
@media (prefers-color-scheme:dark) {
|
|
140
|
+
.git-diff .diff-number { color:#8b949e; border-color:#3a3b3d; }
|
|
141
|
+
.git-diff .diff-addition { background:#033a16; color:#aff5b4; }
|
|
142
|
+
.git-diff .diff-deletion { background:#67060c; color:#ffdcd7; }
|
|
143
|
+
}
|
|
144
|
+
`;
|