@xmanrui/dsh-im 5.10.0 → 5.11.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.
- package/README.en.md +39 -5
- package/README.md +42 -5
- package/bin/dsh-im.mjs +65 -0
- package/docs/client-integration.md +4 -0
- package/lib/client.js +1202 -95
- package/lib/index.js +365 -339
- package/package.json +7 -6
- package/plugin-src/client/access-policy-settings.js +210 -12
- package/plugin-src/client/bot-general-settings.js +44 -3
- package/plugin-src/client/i18n-ru.js +85 -0
- package/plugin-src/client/i18n.js +83 -0
- package/plugin-src/client/im-channels.js +419 -0
- package/plugin-src/client/index.js +33 -1
- package/plugin-src/client/styles.js +7 -7
- package/plugin-src/client/update-panel.js +2 -1
- package/plugin-src/host/channel-list-rpc.mjs +280 -0
- package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
- package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
- package/plugin-src/host/channels/feishu/production.mjs +39 -10
- package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
- package/plugin-src/host/channels/matrix/production.mjs +28 -10
- package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
- package/plugin-src/host/channels/qq/production.mjs +30 -11
- package/plugin-src/host/channels/qq/rpc.mjs +10 -1
- package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
- package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
- package/plugin-src/host/channels/shared/production.mjs +14 -1
- package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/rpc.mjs +9 -0
- package/plugin-src/host/channels/slack/production.mjs +28 -10
- package/plugin-src/host/channels/slack/rpc.mjs +10 -0
- package/plugin-src/host/channels/telegram/production.mjs +5 -0
- package/plugin-src/host/channels/wecom/production.mjs +28 -10
- package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
- package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
- package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
- package/plugin-src/host/channels/weixin/production.mjs +28 -10
- package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
- package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
- package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
- package/plugin-src/host/delivery-service.mjs +3 -4
- package/plugin-src/host/delivery-suggestions.mjs +3 -1
- package/plugin-src/host/harness-connection.mjs +2 -1
- package/plugin-src/host/harness-peer.mjs +3 -1
- package/plugin-src/host/index.mjs +8 -1
- package/plugin-src/host/modern-harness-api.mjs +5 -1
- package/plugin-src/host/root-scope.mjs +32 -0
- package/plugin-src/host/session-sync-coordinator.mjs +2 -1
- package/plugin-src/management-rpc.mjs +18 -2
- package/scripts/verify-package.mjs +36 -7
- package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
- package/src/channels/dingtalk/state-store.mjs +56 -0
- package/src/channels/discord/discord-api.mjs +2 -1
- package/src/channels/feishu/bridge.mjs +154 -58
- package/src/channels/feishu/feishu-cards.mjs +10 -4
- package/src/channels/feishu/feishu-runtime.mjs +11 -3
- package/src/channels/feishu/message-utils.mjs +106 -30
- package/src/channels/feishu/slash-command-panel.mjs +26 -0
- package/src/channels/feishu/state-store.mjs +14 -0
- package/src/channels/matrix/matrix-api.mjs +2 -1
- package/src/channels/qq/qq-bridge.mjs +105 -14
- package/src/channels/qq/state-store.mjs +13 -1
- package/src/channels/shared/access-policy.mjs +60 -7
- package/src/channels/shared/bot-workspace-store.mjs +155 -3
- package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
- package/src/channels/shared/channel-capabilities.mjs +44 -0
- package/src/channels/shared/command-catalog.mjs +68 -3
- package/src/channels/shared/command-permission.mjs +6 -2
- package/src/channels/shared/conversation-state-store.mjs +16 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
- package/src/channels/shared/deferred-delivery.mjs +4 -0
- package/src/channels/shared/diagnostic-details.mjs +6 -1
- package/src/channels/shared/failure-log-file.mjs +79 -0
- package/src/channels/shared/harness-client.mjs +111 -6
- package/src/channels/shared/i18n-en/feishu.mjs +2 -2
- package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
- package/src/channels/shared/i18n-en/shared-b.mjs +67 -4
- package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
- package/src/channels/shared/i18n-en/weixin.mjs +4 -0
- package/src/channels/shared/i18n-en.mjs +2 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
- package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
- package/src/channels/shared/i18n-ru/shared-b.mjs +67 -4
- package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
- package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
- package/src/channels/shared/i18n-ru.mjs +2 -0
- package/src/channels/shared/inbound-access.mjs +10 -0
- package/src/channels/shared/markdown-chunks.mjs +5 -0
- package/src/channels/shared/message-failure.mjs +22 -1
- package/src/channels/shared/new-command.mjs +158 -4
- package/src/channels/shared/plan-goal-command.mjs +132 -0
- package/src/channels/shared/qrcode.mjs +5 -0
- package/src/channels/shared/reply-content.mjs +102 -0
- package/src/channels/shared/reset-command.mjs +46 -0
- package/src/channels/shared/semantic/artifact.mjs +133 -29
- package/src/channels/shared/semantic/reply-reference.mjs +18 -3
- package/src/channels/shared/session-nav-command.mjs +999 -0
- package/src/channels/shared/session-ring-support.mjs +184 -0
- package/src/channels/shared/session-ring.mjs +202 -0
- package/src/channels/shared/session-title.mjs +11 -0
- package/src/channels/shared/status-command.mjs +2 -1
- package/src/channels/shared/text-harness-bridge.mjs +166 -7
- package/src/channels/shared/workspace-command.mjs +567 -31
- package/src/channels/shared/workspace-session.mjs +39 -3
- package/src/channels/slack/slack-api.mjs +2 -1
- package/src/channels/telegram/config-store.mjs +10 -2
- package/src/channels/telegram/telegram-rich-message.mjs +17 -5
- package/src/channels/telegram/telegram-runtime.mjs +14 -1
- package/src/channels/wecom/state-store.mjs +13 -1
- package/src/channels/wecom/wecom-bridge.mjs +183 -26
- package/src/channels/wecom-app/state-store.mjs +13 -1
- package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
- package/src/channels/weixin/state-store.mjs +13 -1
- package/src/channels/weixin/weixin-bridge.mjs +71 -4
|
@@ -0,0 +1,999 @@
|
|
|
1
|
+
import { t } from './i18n.mjs';
|
|
2
|
+
import { conversationSessionWorkspace, splitWorkspaceCommandMessage } from './workspace-command.mjs';
|
|
3
|
+
import { isSessionNotFound } from './session-error.mjs';
|
|
4
|
+
import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
|
|
5
|
+
import { safeCodeFence } from './markdown-chunks.mjs';
|
|
6
|
+
import { normalizeSessionTitle } from './session-title.mjs';
|
|
7
|
+
import {
|
|
8
|
+
navigateSessionRing,
|
|
9
|
+
renameSessionRingEntry,
|
|
10
|
+
sessionRingBackTarget,
|
|
11
|
+
sessionRingEntryByNumber,
|
|
12
|
+
sessionRingEntryBySessionId,
|
|
13
|
+
sessionRingForwardTarget,
|
|
14
|
+
stepSessionRingTo,
|
|
15
|
+
} from './session-ring.mjs';
|
|
16
|
+
|
|
17
|
+
const SESSION_NAV_COMMAND = /^\/(?:ls|list|go|prev|next|drop|title|tail|peek|fork)(?=$|\s)/iu;
|
|
18
|
+
const GO_COMMAND = /^\/go\s+(\d+)(?:\s+([\s\S]+))?$/iu;
|
|
19
|
+
const PREV_COMMAND = /^\/prev(?:\s+([\s\S]+))?$/iu;
|
|
20
|
+
const NEXT_COMMAND = /^\/next(?:\s+([\s\S]+))?$/iu;
|
|
21
|
+
const DROP_COMMAND = /^\/drop[ \t]+(\d+|all|\*)$/iu;
|
|
22
|
+
const TITLE_COMMAND = /^\/title(?:\s+([\s\S]+))?$/iu;
|
|
23
|
+
const TAIL_COMMAND = /^\/(?:tail|peek)(?:\s+([\s\S]+))?$/iu;
|
|
24
|
+
const FORK_COMMAND = /^\/fork(?:\s+([\s\S]+))?$/iu;
|
|
25
|
+
|
|
26
|
+
const DEFAULT_TAIL_COUNT = 5;
|
|
27
|
+
const MAX_TAIL_COUNT = 50;
|
|
28
|
+
const TAIL_PAGE_SIZE = 50;
|
|
29
|
+
const TAIL_READ_TIMEOUT_MS = 10_000;
|
|
30
|
+
const TAIL_EXPORT_EVENT_CAP = 5_000;
|
|
31
|
+
const TAIL_TOTAL_BUDGET = 4_000;
|
|
32
|
+
const RING_LIST_LIMIT = 20;
|
|
33
|
+
|
|
34
|
+
const INJECTED_CONTEXT_PREFIX = /^(?:<dsh_im_source>[\s\S]*?<\/dsh_im_source>\s*)?(?:<dsh_im_source_guidance>[\s\S]*?<\/dsh_im_source_guidance>\s*)?(?:<dsh_im_reply_to>[\s\S]*?<\/dsh_im_reply_to>\s*)?/u;
|
|
35
|
+
|
|
36
|
+
export function isSessionNavCommand(text) {
|
|
37
|
+
return typeof text === 'string' && SESSION_NAV_COMMAND.test(text.trim());
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Single source of truth for the /ls marker glyphs (no VS16, fixed width). */
|
|
41
|
+
export const SESSION_MARKERS = Object.freeze({
|
|
42
|
+
current: '●',
|
|
43
|
+
ordinary: '·',
|
|
44
|
+
dead: '✕',
|
|
45
|
+
back: '←',
|
|
46
|
+
forward: '→',
|
|
47
|
+
both: '⇄',
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
/** Marker for one ring entry given the computed back/forward targets. */
|
|
51
|
+
function sessionMarker(entry, markers, availabilityState) {
|
|
52
|
+
if (availabilityState === 'deleted' || availabilityState === 'archived') return SESSION_MARKERS.dead;
|
|
53
|
+
if (markers?.currentSessionId && entry.sessionId === markers.currentSessionId) return SESSION_MARKERS.current;
|
|
54
|
+
if (markers?.backTarget != null
|
|
55
|
+
&& markers.backTarget === markers.forwardTarget
|
|
56
|
+
&& entry.n === markers.backTarget) {
|
|
57
|
+
return SESSION_MARKERS.both;
|
|
58
|
+
}
|
|
59
|
+
if (entry.n === markers?.backTarget) return SESSION_MARKERS.back;
|
|
60
|
+
if (entry.n === markers?.forwardTarget) return SESSION_MARKERS.forward;
|
|
61
|
+
return SESSION_MARKERS.ordinary;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `●4` style number: marker + entry number, so glyphs cannot drift. */
|
|
65
|
+
export function renderSessionNumber(entry, markers, availabilityState = 'alive') {
|
|
66
|
+
return `${sessionMarker(entry, markers, availabilityState)}${entry.n}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function commandResult(message, extra = {}) {
|
|
70
|
+
return {
|
|
71
|
+
handled: true,
|
|
72
|
+
message,
|
|
73
|
+
messages: splitWorkspaceCommandMessage(message),
|
|
74
|
+
document: null,
|
|
75
|
+
hide: false,
|
|
76
|
+
...extra,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function documentResult(document) {
|
|
81
|
+
return { handled: true, message: null, messages: [], document, hide: false };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function sortedEvents(events) {
|
|
85
|
+
return [...events.values()].sort((left, right) => left.seq - right.seq);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function formatAgeNumber(value) {
|
|
89
|
+
if (value < 10) {
|
|
90
|
+
const rounded = Math.round(value * 10) / 10;
|
|
91
|
+
return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
|
|
92
|
+
}
|
|
93
|
+
return String(Math.round(value));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Compact age of last activity with one localized unit, e.g. 70 сек / 10 мин / 3.5 ч / 2 д. */
|
|
97
|
+
export function formatAge(ms, now = Date.now()) {
|
|
98
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return '—';
|
|
99
|
+
const delta = Math.max(0, now - ms);
|
|
100
|
+
const seconds = delta / 1_000;
|
|
101
|
+
if (seconds < 90) return `${Math.floor(seconds)} ${t('秒')}`;
|
|
102
|
+
const minutes = seconds / 60;
|
|
103
|
+
if (minutes < 90) return `${formatAgeNumber(minutes)} ${t('分')}`;
|
|
104
|
+
const hours = minutes / 60;
|
|
105
|
+
if (hours < 36) return `${formatAgeNumber(hours)} ${t('时')}`;
|
|
106
|
+
return `${formatAgeNumber(hours / 24)} ${t('天')}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function messageText(content) {
|
|
110
|
+
if (typeof content === 'string') return content;
|
|
111
|
+
if (!Array.isArray(content)) return '';
|
|
112
|
+
return content
|
|
113
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
114
|
+
.map((block) => block.text)
|
|
115
|
+
.join('\n');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function stripInjectedPrefix(text) {
|
|
119
|
+
return typeof text === 'string' ? text.replace(INJECTED_CONTEXT_PREFIX, '') : text;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Reduce a session event stream to user prompts and assistant final answers.
|
|
124
|
+
* Tool calls, tool results, system events, injected plugin context and subagent
|
|
125
|
+
* traffic are all dropped; consecutive fragments of the same role merge.
|
|
126
|
+
*/
|
|
127
|
+
export function tailMessages(events) {
|
|
128
|
+
const ordered = [];
|
|
129
|
+
const assistants = new Map();
|
|
130
|
+
for (const event of events) {
|
|
131
|
+
const data = event?.data;
|
|
132
|
+
if (event?.type === 'user/message' && event?.surfaceOp === 'append'
|
|
133
|
+
&& data?.source?.kind === 'user') {
|
|
134
|
+
ordered.push({ role: 'user', text: stripInjectedPrefix(messageText(data.content)) });
|
|
135
|
+
} else if (event?.type === 'assistant/message' && event?.surfaceOp === 'append'
|
|
136
|
+
&& Number.isSafeInteger(data?.turn) && data.turn >= 0) {
|
|
137
|
+
assistants.set(data.turn, event);
|
|
138
|
+
} else if (event?.type === 'turn/end') {
|
|
139
|
+
const assistant = assistants.get(data?.turn);
|
|
140
|
+
assistants.delete(data?.turn);
|
|
141
|
+
if ((data?.reason?.kind ?? data?.reason) !== 'completed'
|
|
142
|
+
|| !assistant || assistant.data.interrupted === true) continue;
|
|
143
|
+
ordered.push({ role: 'assistant', text: messageText(assistant.data.message?.content) });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const merged = [];
|
|
147
|
+
for (const message of ordered) {
|
|
148
|
+
const last = merged[merged.length - 1];
|
|
149
|
+
if (last && last.role === message.role) last.text = `${last.text}\n${message.text}`;
|
|
150
|
+
else merged.push(message);
|
|
151
|
+
}
|
|
152
|
+
return merged;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Page backwards over a session's history, stopping when `stop(events)` turns
|
|
157
|
+
* true or the session is exhausted. Returns the collected events plus why the
|
|
158
|
+
* loop ended, so a preview and an export can interpret the two exits correctly.
|
|
159
|
+
*/
|
|
160
|
+
async function readTailEvents(session, { signal, stop }) {
|
|
161
|
+
const events = new Map();
|
|
162
|
+
let beforeSeq;
|
|
163
|
+
const deadline = Date.now() + TAIL_READ_TIMEOUT_MS;
|
|
164
|
+
for (;;) {
|
|
165
|
+
signal?.throwIfAborted();
|
|
166
|
+
if (Date.now() >= deadline) throw new DOMException('Tail read timed out', 'TimeoutError');
|
|
167
|
+
const page = await session.readHistory({
|
|
168
|
+
maxMessages: TAIL_PAGE_SIZE,
|
|
169
|
+
...(beforeSeq === undefined ? {} : { beforeSeq }),
|
|
170
|
+
timeoutMs: Math.max(1, deadline - Date.now()),
|
|
171
|
+
signal,
|
|
172
|
+
});
|
|
173
|
+
signal?.throwIfAborted();
|
|
174
|
+
if (!page || !Array.isArray(page.events) || typeof page.hasMore !== 'boolean') {
|
|
175
|
+
throw new TypeError('Invalid history page');
|
|
176
|
+
}
|
|
177
|
+
let oldestSeq = beforeSeq ?? Infinity;
|
|
178
|
+
let advanced = false;
|
|
179
|
+
for (const entry of page.events) {
|
|
180
|
+
const event = entry?.event;
|
|
181
|
+
if (!event || !Number.isSafeInteger(event.seq) || event.seq < 0
|
|
182
|
+
|| typeof event.type !== 'string' || !event.type) {
|
|
183
|
+
throw new TypeError('Invalid history event');
|
|
184
|
+
}
|
|
185
|
+
if (beforeSeq !== undefined && event.seq >= beforeSeq) continue;
|
|
186
|
+
if (events.has(event.seq)) continue;
|
|
187
|
+
events.set(event.seq, event);
|
|
188
|
+
advanced = true;
|
|
189
|
+
oldestSeq = Math.min(oldestSeq, event.seq);
|
|
190
|
+
}
|
|
191
|
+
if (stop && stop(events)) return { events, stopped: true, exhausted: false };
|
|
192
|
+
if (!page.hasMore) return { events, stopped: false, exhausted: true };
|
|
193
|
+
if (!advanced || oldestSeq === beforeSeq) throw new TypeError('History cursor did not advance');
|
|
194
|
+
beforeSeq = oldestSeq;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function truncateToBudget(text, { maxLines, maxChars }) {
|
|
199
|
+
if (typeof text !== 'string' || !text) return '';
|
|
200
|
+
const lines = text.split('\n');
|
|
201
|
+
let out = '';
|
|
202
|
+
let usedLines = 0;
|
|
203
|
+
for (const line of lines) {
|
|
204
|
+
if (usedLines >= maxLines) break;
|
|
205
|
+
const remaining = maxChars - out.length;
|
|
206
|
+
if (remaining <= 0) break;
|
|
207
|
+
const segment = line.length > remaining ? `${line.slice(0, Math.max(0, remaining - 1))}…` : line;
|
|
208
|
+
out += (usedLines === 0 ? '' : '\n') + segment;
|
|
209
|
+
usedLines += 1;
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function renderTailPreview(messages, { count, n }) {
|
|
215
|
+
const budget = count <= 10
|
|
216
|
+
? { maxLines: 3, maxChars: 300 }
|
|
217
|
+
: { maxLines: 1, maxChars: 100 };
|
|
218
|
+
const header = n === null
|
|
219
|
+
? t('当前会话最近 {count} 条(仅显示提问与回答):', { count: messages.length })
|
|
220
|
+
: t('会话 {n} 最近 {count} 条(仅显示提问与回答):', { n, count: messages.length });
|
|
221
|
+
const lines = [header];
|
|
222
|
+
let total = header.length;
|
|
223
|
+
let shown = 0;
|
|
224
|
+
for (const message of [...messages].reverse()) {
|
|
225
|
+
const label = message.role === 'user' ? t('用户') : t('助手');
|
|
226
|
+
const block = `${label}\n${truncateToBudget(message.text, budget)}`;
|
|
227
|
+
if (total + block.length + 2 > TAIL_TOTAL_BUDGET) break;
|
|
228
|
+
lines.push(block);
|
|
229
|
+
total += block.length + 2;
|
|
230
|
+
shown += 1;
|
|
231
|
+
}
|
|
232
|
+
const hidden = messages.length - shown;
|
|
233
|
+
if (hidden > 0) lines.push(t('… 还有 {n} 条更早的消息。', { n: hidden }));
|
|
234
|
+
return lines.join('\n\n');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function tailErrorMessage(error) {
|
|
238
|
+
const code = error?.code ?? error?.failure?.code;
|
|
239
|
+
if (isSessionNotFound(code)) return t('当前聊天绑定的会话已不存在,请重新绑定会话。');
|
|
240
|
+
if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found'
|
|
241
|
+
|| code === 'session-binding-changed') {
|
|
242
|
+
return t('会话、工作区或机器人状态已发生变化,请重新执行 /tail。');
|
|
243
|
+
}
|
|
244
|
+
if (code === 'harness-api-not-found') return t('当前 Harness 暂不支持读取会话历史。');
|
|
245
|
+
if (error?.name === 'AbortError') return t('读取已取消。');
|
|
246
|
+
if (error?.name === 'TimeoutError' || code === 'harness-timeout') return t('读取超时,请稍后重试。');
|
|
247
|
+
return t('暂时无法读取会话内容,请稍后重试。');
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Best-effort availability: 'alive' = exists and bindable, 'archived' = exists
|
|
252
|
+
* but cannot be bound, 'deleted' = no longer exists, null = unknown.
|
|
253
|
+
*/
|
|
254
|
+
async function entryAvailability(harness, key, sessionId, signal) {
|
|
255
|
+
try {
|
|
256
|
+
const session = typeof harness?.workspaceSession === 'function'
|
|
257
|
+
? harness.workspaceSession(sessionId, key)
|
|
258
|
+
: null;
|
|
259
|
+
if (!session || typeof session.sessionExists !== 'function') return null;
|
|
260
|
+
signal?.throwIfAborted();
|
|
261
|
+
if ((await session.sessionExists()) === false) return 'deleted';
|
|
262
|
+
if (typeof harness?.isSessionArchived === 'function') {
|
|
263
|
+
signal?.throwIfAborted();
|
|
264
|
+
if (await harness.isSessionArchived(sessionId, { signal }) === true) return 'archived';
|
|
265
|
+
}
|
|
266
|
+
return 'alive';
|
|
267
|
+
} catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function unknownEntryResult(n) {
|
|
273
|
+
return commandResult(t('没有编号为 {n} 的会话。用 /ls 查看列表。', { n }));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Best-effort title + last-activity for one Session, read from the Host. */
|
|
277
|
+
async function fetchSessionInfoFromHost(harness, key, sessionId, signal) {
|
|
278
|
+
if (typeof harness?.listWorkspaceSessions !== 'function') return null;
|
|
279
|
+
try {
|
|
280
|
+
const workspace = await conversationSessionWorkspace(harness, key, { signal });
|
|
281
|
+
if (!workspace) return null;
|
|
282
|
+
signal?.throwIfAborted();
|
|
283
|
+
const listed = await harness.listWorkspaceSessions(workspace, { signal });
|
|
284
|
+
const session = Array.isArray(listed?.sessions)
|
|
285
|
+
? listed.sessions.find((candidate) => candidate?.sessionId === sessionId)
|
|
286
|
+
: null;
|
|
287
|
+
if (!session) return null;
|
|
288
|
+
return {
|
|
289
|
+
title: typeof session.title === 'string' && session.title ? session.title : null,
|
|
290
|
+
lastSeenAt: Number.isFinite(session.time) ? session.time : null,
|
|
291
|
+
};
|
|
292
|
+
} catch {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Batch Host titles for a list of Session ids, so /ls can surface them. */
|
|
298
|
+
async function hostSessionTitles(harness, key, sessionIds, signal) {
|
|
299
|
+
const titles = new Map();
|
|
300
|
+
if (typeof harness?.listWorkspaceSessions !== 'function' || sessionIds.length === 0) return titles;
|
|
301
|
+
try {
|
|
302
|
+
const workspace = await conversationSessionWorkspace(harness, key, { signal });
|
|
303
|
+
if (!workspace) return titles;
|
|
304
|
+
signal?.throwIfAborted();
|
|
305
|
+
const listed = await harness.listWorkspaceSessions(workspace, { signal });
|
|
306
|
+
for (const session of listed?.sessions ?? []) {
|
|
307
|
+
if (session?.sessionId && typeof session.title === 'string' && session.title) {
|
|
308
|
+
titles.set(session.sessionId, session.title);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
} catch {
|
|
312
|
+
// titles are best-effort
|
|
313
|
+
}
|
|
314
|
+
return titles;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* The currently bound Session must always be in the ring. A chat bound before
|
|
319
|
+
* this feature shipped has a binding but no ring entry, so the first navigation
|
|
320
|
+
* command registers it lazily (number = next free, title and last-activity from
|
|
321
|
+
* the Host).
|
|
322
|
+
*/
|
|
323
|
+
async function ensureCurrentSessionInRing(state, harness, key, { signal }) {
|
|
324
|
+
const sessionId = state?.sessionFor?.(key);
|
|
325
|
+
if (!sessionId) return null;
|
|
326
|
+
const ring = state?.ringFor?.(key);
|
|
327
|
+
if (ring) {
|
|
328
|
+
const existing = sessionRingEntryBySessionId(ring, sessionId);
|
|
329
|
+
if (existing) return existing;
|
|
330
|
+
}
|
|
331
|
+
const info = await fetchSessionInfoFromHost(harness, key, sessionId, signal);
|
|
332
|
+
const result = await state?.ensureSessionRing?.(key, sessionId, {
|
|
333
|
+
title: info?.title ?? undefined,
|
|
334
|
+
lastSeenAt: info?.lastSeenAt ?? undefined,
|
|
335
|
+
});
|
|
336
|
+
return result?.entry ?? null;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Enforce the ring invariant before rendering: visits[visitIndex] must be the
|
|
341
|
+
* entry of the Session currently bound. A binding made outside /go//prev//next
|
|
342
|
+
* (eager /new, /session adopt, a reused Session) can leave the visit stack
|
|
343
|
+
* stale, so the current entry is appended as the current position.
|
|
344
|
+
*/
|
|
345
|
+
async function repairRingCurrent(state, key) {
|
|
346
|
+
const sessionId = state?.sessionFor?.(key);
|
|
347
|
+
if (!sessionId) return;
|
|
348
|
+
const ring = state?.ringFor?.(key);
|
|
349
|
+
if (!ring) return;
|
|
350
|
+
const entry = sessionRingEntryBySessionId(ring, sessionId);
|
|
351
|
+
if (!entry) return;
|
|
352
|
+
const visitCurrent = ring.visitIndex >= 0 ? ring.visits[ring.visitIndex] : null;
|
|
353
|
+
if (visitCurrent !== entry.n) await state?.appendRing?.(key, entry.n);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Cap a title at ~30 characters for the /ls line, appending an ellipsis. */
|
|
357
|
+
function truncateListTitle(title) {
|
|
358
|
+
const text = typeof title === 'string' && title ? title : t('无标题');
|
|
359
|
+
const chars = [...text];
|
|
360
|
+
return chars.length > 30 ? `${chars.slice(0, 29).join('')}…` : text;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function goErrorMessage(error, n) {
|
|
364
|
+
const code = error?.code ?? error?.failure?.code;
|
|
365
|
+
if (isSessionNotFound(code) || code === 'session-not-registered'
|
|
366
|
+
|| code === 'session-archived' || code === 'session-summary-unavailable') {
|
|
367
|
+
return t('编号 {n} 的会话已不存在或已归档。如需从列表移除请发送 /drop {n}。', { n });
|
|
368
|
+
}
|
|
369
|
+
if (code === 'workspace-bot-not-found' || code === WORKSPACE_SESSION_STALE
|
|
370
|
+
|| code === 'session-conflict' || code === 'workspace-conflict'
|
|
371
|
+
|| code === 'session-binding-changed') {
|
|
372
|
+
return t('工作区或机器人状态已发生变化,请重试 /go {n}。', { n });
|
|
373
|
+
}
|
|
374
|
+
return t('暂时无法切换会话,请稍后重试。');
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function runList(state, harness, key, { signal }) {
|
|
378
|
+
await repairRingCurrent(state, key);
|
|
379
|
+
const ring = state?.ringFor?.(key);
|
|
380
|
+
if (!ring || ring.entries.length === 0) {
|
|
381
|
+
return commandResult(t('此聊天或话题还没有会话,发送 /new 创建第一个(列表按聊天隔离,论坛群按话题)。'));
|
|
382
|
+
}
|
|
383
|
+
const markers = await computeRingMarkers(state, harness, key, { signal });
|
|
384
|
+
const currentSessionId = markers.currentSessionId;
|
|
385
|
+
const windowEntries = ring.entries.length > RING_LIST_LIMIT
|
|
386
|
+
? ring.entries.slice(-RING_LIST_LIMIT)
|
|
387
|
+
: ring.entries;
|
|
388
|
+
const currentEntry = currentSessionId
|
|
389
|
+
? ring.entries.find((entry) => entry.sessionId === currentSessionId)
|
|
390
|
+
: null;
|
|
391
|
+
const currentInWindow = currentEntry
|
|
392
|
+
? windowEntries.some((entry) => entry.n === currentEntry.n)
|
|
393
|
+
: true;
|
|
394
|
+
const renderEntries = currentEntry && !currentInWindow
|
|
395
|
+
? [...windowEntries, currentEntry]
|
|
396
|
+
: windowEntries;
|
|
397
|
+
const availability = new Map();
|
|
398
|
+
await Promise.all(renderEntries.map(async (entry) => {
|
|
399
|
+
availability.set(entry.n, await entryAvailability(harness, key, entry.sessionId, signal));
|
|
400
|
+
}));
|
|
401
|
+
// Surface the Host title (including its first-prompt fallback) for entries the
|
|
402
|
+
// ring has no title for yet.
|
|
403
|
+
const titles = await hostSessionTitles(harness, key, renderEntries.map((entry) => entry.sessionId), signal);
|
|
404
|
+
const parts = [t('会话(/go N):')];
|
|
405
|
+
if (ring.entries.length > RING_LIST_LIMIT) {
|
|
406
|
+
parts.push(t('会话较多,仅显示最近 {shown} 条(共 {total} 条)。', {
|
|
407
|
+
shown: windowEntries.length,
|
|
408
|
+
total: ring.entries.length,
|
|
409
|
+
}));
|
|
410
|
+
}
|
|
411
|
+
for (const entry of windowEntries) {
|
|
412
|
+
const availabilityState = availability.get(entry.n);
|
|
413
|
+
const marker = sessionMarker(entry, markers, availabilityState);
|
|
414
|
+
const title = entry.title || titles.get(entry.sessionId) || null;
|
|
415
|
+
parts.push(`${marker} ${entry.n}. ${formatAge(entry.lastSeenAt)}, ${truncateListTitle(title)}`);
|
|
416
|
+
}
|
|
417
|
+
// A bound entry older than the tail window must still be visible, once.
|
|
418
|
+
if (currentEntry && !currentInWindow) {
|
|
419
|
+
parts.push('…');
|
|
420
|
+
const availabilityState = availability.get(currentEntry.n);
|
|
421
|
+
const marker = sessionMarker(currentEntry, markers, availabilityState);
|
|
422
|
+
const title = currentEntry.title || titles.get(currentEntry.sessionId) || null;
|
|
423
|
+
parts.push(`${marker} ${currentEntry.n}. ${formatAge(currentEntry.lastSeenAt)}, ${truncateListTitle(title)}`);
|
|
424
|
+
}
|
|
425
|
+
if (currentEntry) {
|
|
426
|
+
const currentState = availability.get(currentEntry.n)
|
|
427
|
+
?? await entryAvailability(harness, key, currentEntry.sessionId, signal);
|
|
428
|
+
if (currentState === 'deleted' || currentState === 'archived') {
|
|
429
|
+
parts.push(t('✕ 当前会话已失效,发送 /new 可开启新会话。'));
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return commandResult(parts.join('\n\n'));
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Bind the conversation to one Session and verify the binding really changed.
|
|
437
|
+
* A bot-scoped bind can return success while a stale scope refused the actual
|
|
438
|
+
* setSession; reporting that as a switch would strand the user on the old
|
|
439
|
+
* (possibly archived) Session. Throws a classified error on any mismatch.
|
|
440
|
+
*/
|
|
441
|
+
async function bindToSession(harness, state, key, sessionId) {
|
|
442
|
+
const bound = await harness.bindWorkspaceSession(key, sessionId, { navigation: true });
|
|
443
|
+
if (bound?.archived === true) {
|
|
444
|
+
const error = new Error('The Session is archived and cannot be bound');
|
|
445
|
+
error.code = 'session-archived';
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
448
|
+
const current = state?.sessionFor?.(key) ?? null;
|
|
449
|
+
if (current !== sessionId || bound?.sessionId !== sessionId) {
|
|
450
|
+
const error = new Error('The session binding did not change');
|
|
451
|
+
error.code = 'session-binding-changed';
|
|
452
|
+
throw error;
|
|
453
|
+
}
|
|
454
|
+
return bound;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Pick the next live entry for /prev or /next: the visit-stack target first,
|
|
459
|
+
* then the ring's other entries by last activity (most recent first for back,
|
|
460
|
+
* least recent first for forward). Dead entries are stepped over; null means
|
|
461
|
+
* there is no live entry left in that direction.
|
|
462
|
+
*/
|
|
463
|
+
async function liveStepTarget(ring, direction, currentSessionId, availabilityOf) {
|
|
464
|
+
const fromStack = direction === 'back' ? sessionRingBackTarget(ring) : sessionRingForwardTarget(ring);
|
|
465
|
+
const others = ring.entries
|
|
466
|
+
.filter((entry) => entry.sessionId !== currentSessionId)
|
|
467
|
+
.sort((left, right) => (right.lastSeenAt ?? 0) - (left.lastSeenAt ?? 0));
|
|
468
|
+
const ordered = direction === 'back' ? others : [...others].reverse();
|
|
469
|
+
const candidates = [];
|
|
470
|
+
if (fromStack !== null) candidates.push({ n: fromStack, fromStack: true });
|
|
471
|
+
for (const entry of ordered) {
|
|
472
|
+
if (!candidates.some((candidate) => candidate.n === entry.n)) {
|
|
473
|
+
candidates.push({ n: entry.n, fromStack: false });
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
for (const candidate of candidates) {
|
|
477
|
+
const entry = sessionRingEntryByNumber(ring, candidate.n);
|
|
478
|
+
if (!entry) continue;
|
|
479
|
+
const availability = await availabilityOf(entry.sessionId);
|
|
480
|
+
if (availability === 'deleted' || availability === 'archived') continue;
|
|
481
|
+
return candidate;
|
|
482
|
+
}
|
|
483
|
+
return null;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Compute the /prev and /next targets with the exact same code the commands
|
|
488
|
+
* use (visit trail first, then fallback by last activity, skipping dead
|
|
489
|
+
* entries). /ls and reply texts both render arrows from this, so an arrow can
|
|
490
|
+
* never claim a move the command would refuse.
|
|
491
|
+
*/
|
|
492
|
+
async function computeRingMarkers(state, harness, key, { signal }) {
|
|
493
|
+
const ring = state?.ringFor?.(key);
|
|
494
|
+
const currentSessionId = state?.sessionFor?.(key) ?? null;
|
|
495
|
+
if (!ring || !currentSessionId) return { currentSessionId, backTarget: null, forwardTarget: null };
|
|
496
|
+
const availabilityOf = (sessionId) => entryAvailability(harness, key, sessionId, signal);
|
|
497
|
+
const back = await liveStepTarget(ring, 'back', currentSessionId, availabilityOf);
|
|
498
|
+
const forward = await liveStepTarget(ring, 'forward', currentSessionId, availabilityOf);
|
|
499
|
+
return {
|
|
500
|
+
currentSessionId,
|
|
501
|
+
backTarget: back?.n ?? null,
|
|
502
|
+
forwardTarget: forward?.n ?? null,
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async function runGo(state, harness, key, n, { signal, askText = null }) {
|
|
507
|
+
const ring = state?.ringFor?.(key);
|
|
508
|
+
const entry = ring ? sessionRingEntryByNumber(ring, n) : null;
|
|
509
|
+
if (!entry) return unknownEntryResult(n);
|
|
510
|
+
if (typeof harness?.bindWorkspaceSession !== 'function') {
|
|
511
|
+
return commandResult(t('当前机器人暂不支持绑定已有会话。'));
|
|
512
|
+
}
|
|
513
|
+
try {
|
|
514
|
+
await bindToSession(harness, state, key, entry.sessionId);
|
|
515
|
+
await state?.navigateRing?.(key, n);
|
|
516
|
+
const after = state?.ringFor?.(key);
|
|
517
|
+
const fresh = after ? sessionRingEntryByNumber(after, n) : entry;
|
|
518
|
+
const markers = await computeRingMarkers(state, harness, key, { signal });
|
|
519
|
+
const label = fresh ? renderSessionNumber(fresh, markers) : n;
|
|
520
|
+
return commandResult(t('已切换到会话 {n}({title},最后活动 {age})。', {
|
|
521
|
+
n: label,
|
|
522
|
+
title: fresh?.title || t('无标题'),
|
|
523
|
+
age: formatAge(fresh?.lastSeenAt),
|
|
524
|
+
}), typeof askText === 'string' && askText ? { askText } : {});
|
|
525
|
+
} catch (error) {
|
|
526
|
+
return commandResult(goErrorMessage(error, n));
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
async function runStep(state, harness, key, direction, { signal, askText = null }) {
|
|
531
|
+
const ring = state?.ringFor?.(key);
|
|
532
|
+
if (!ring || ring.entries.length === 0) {
|
|
533
|
+
return commandResult(t('此聊天或话题还没有会话,发送 /new 创建第一个(列表按聊天隔离,论坛群按话题)。'));
|
|
534
|
+
}
|
|
535
|
+
if (typeof harness?.bindWorkspaceSession !== 'function') {
|
|
536
|
+
return commandResult(t('当前机器人暂不支持绑定已有会话。'));
|
|
537
|
+
}
|
|
538
|
+
const currentSessionId = state?.sessionFor?.(key) ?? null;
|
|
539
|
+
const target = await liveStepTarget(ring, direction, currentSessionId, (sessionId) => (
|
|
540
|
+
entryAvailability(harness, key, sessionId, signal)
|
|
541
|
+
));
|
|
542
|
+
if (target === null) {
|
|
543
|
+
return commandResult(direction === 'back' ? t('此聊天没有更早的会话。') : t('此聊天没有更晚的会话。'));
|
|
544
|
+
}
|
|
545
|
+
const entry = sessionRingEntryByNumber(ring, target.n);
|
|
546
|
+
if (!entry) return commandResult(t('目标会话不存在,请发送 /ls 查看。'));
|
|
547
|
+
try {
|
|
548
|
+
await bindToSession(harness, state, key, entry.sessionId);
|
|
549
|
+
if (target.fromStack) await state?.stepRingTo?.(key, target.n);
|
|
550
|
+
else await state?.appendRing?.(key, target.n);
|
|
551
|
+
const markers = await computeRingMarkers(state, harness, key, { signal });
|
|
552
|
+
const label = renderSessionNumber(entry, markers);
|
|
553
|
+
return commandResult(t('已切换到会话 {n}({title})。', { n: label, title: entry.title || t('无标题') }),
|
|
554
|
+
typeof askText === 'string' && askText ? { askText } : {});
|
|
555
|
+
} catch (error) {
|
|
556
|
+
return commandResult(goErrorMessage(error, target.n));
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async function runDrop(state, harness, key, n, { signal }) {
|
|
561
|
+
const ring = state?.ringFor?.(key);
|
|
562
|
+
const entry = ring ? sessionRingEntryByNumber(ring, n) : null;
|
|
563
|
+
if (!entry) return unknownEntryResult(n);
|
|
564
|
+
const currentSessionId = state?.sessionFor?.(key) ?? null;
|
|
565
|
+
if (entry.sessionId === currentSessionId) {
|
|
566
|
+
return commandResult(t('编号 {n} 是当前会话,不能删除。请先切换到其他会话(/go 数字、/prev 或 /new)再删除。', { n }));
|
|
567
|
+
}
|
|
568
|
+
const availabilityState = await entryAvailability(harness, key, entry.sessionId, signal);
|
|
569
|
+
const removed = await state?.dropSessionRing?.(key, n);
|
|
570
|
+
if (removed === false) return unknownEntryResult(n);
|
|
571
|
+
const label = renderSessionNumber(entry, { currentSessionId, backTarget: null, forwardTarget: null }, availabilityState);
|
|
572
|
+
return commandResult(t('已从会话列表移除编号 {n}。注意:Harness 中的会话本身未被删除或归档,仍可在 DSH 中访问。', { n: label }));
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** /drop all: keep only the bound entry; the sessions themselves are untouched. */
|
|
576
|
+
async function runDropAll(state, key) {
|
|
577
|
+
const ring = state?.ringFor?.(key);
|
|
578
|
+
const currentSessionId = state?.sessionFor?.(key) ?? null;
|
|
579
|
+
const currentEntry = currentSessionId && ring
|
|
580
|
+
? sessionRingEntryBySessionId(ring, currentSessionId)
|
|
581
|
+
: null;
|
|
582
|
+
if (!currentEntry) {
|
|
583
|
+
return commandResult(t('当前聊天尚未绑定会话,无法确定保留哪条,未移除任何记录。'));
|
|
584
|
+
}
|
|
585
|
+
const others = ring.entries.filter((entry) => entry.n !== currentEntry.n);
|
|
586
|
+
if (others.length === 0) {
|
|
587
|
+
return commandResult(t('列表里只有当前会话,无需移除。'));
|
|
588
|
+
}
|
|
589
|
+
const removed = await state?.dropSessionRingAllExcept?.(key, currentEntry.n);
|
|
590
|
+
return commandResult(t('已移除 {count} 条记录,保留编号 {n}(当前会话)。注意:Harness 中的会话本身未被删除或归档,仍可在 DSH 中访问。', {
|
|
591
|
+
count: removed,
|
|
592
|
+
n: currentEntry.n,
|
|
593
|
+
}));
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function parseTitleArgument(raw) {
|
|
597
|
+
const text = typeof raw === 'string' ? raw.trim() : '';
|
|
598
|
+
if (!text) return { show: true, n: null };
|
|
599
|
+
const numeric = /^(\d+)$/u.exec(text);
|
|
600
|
+
if (numeric) return { show: true, n: Number(numeric[1]) };
|
|
601
|
+
const withNumber = /^(\d+)\s+([\s\S]+)$/u.exec(text);
|
|
602
|
+
if (withNumber) return { show: false, n: Number(withNumber[1]), title: withNumber[2].trim() };
|
|
603
|
+
return { show: false, n: null, title: text };
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
async function renameSessionTitle(harness, key, sessionId, title) {
|
|
607
|
+
const session = typeof harness?.workspaceSession === 'function'
|
|
608
|
+
? harness.workspaceSession(sessionId, key)
|
|
609
|
+
: null;
|
|
610
|
+
if (session && typeof session.renameTitle === 'function') {
|
|
611
|
+
await session.renameTitle(title);
|
|
612
|
+
return true;
|
|
613
|
+
}
|
|
614
|
+
if (typeof harness?.renameSession === 'function') {
|
|
615
|
+
await harness.renameSession(sessionId, title);
|
|
616
|
+
return true;
|
|
617
|
+
}
|
|
618
|
+
return false;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
async function runTitle(state, harness, key, raw, { signal }) {
|
|
622
|
+
const parsed = parseTitleArgument(raw);
|
|
623
|
+
const ring = state?.ringFor?.(key);
|
|
624
|
+
if (parsed.show) {
|
|
625
|
+
if (parsed.n !== null) {
|
|
626
|
+
const entry = ring ? sessionRingEntryByNumber(ring, parsed.n) : null;
|
|
627
|
+
if (!entry) return unknownEntryResult(parsed.n);
|
|
628
|
+
const markers = await computeRingMarkers(state, harness, key, { signal });
|
|
629
|
+
const availabilityState = await entryAvailability(harness, key, entry.sessionId, signal);
|
|
630
|
+
return commandResult(t('会话 {n}:{title}', {
|
|
631
|
+
n: renderSessionNumber(entry, markers, availabilityState),
|
|
632
|
+
title: entry.title || t('无标题'),
|
|
633
|
+
}));
|
|
634
|
+
}
|
|
635
|
+
const currentSessionId = state?.sessionFor?.(key) ?? null;
|
|
636
|
+
if (!currentSessionId) return commandResult(t('当前聊天尚未绑定会话。'));
|
|
637
|
+
const current = ring ? sessionRingEntryBySessionId(ring, currentSessionId) : null;
|
|
638
|
+
let title = current?.title ?? null;
|
|
639
|
+
if (!title) {
|
|
640
|
+
const info = await fetchSessionInfoFromHost(harness, key, currentSessionId, signal);
|
|
641
|
+
title = info?.title ?? null;
|
|
642
|
+
if (title && current) await state?.renameSessionRing?.(key, current.n, title);
|
|
643
|
+
}
|
|
644
|
+
const label = title || t('无标题');
|
|
645
|
+
if (current) {
|
|
646
|
+
const markers = await computeRingMarkers(state, harness, key, { signal });
|
|
647
|
+
return commandResult(t('当前会话编号 {n}:{title}', {
|
|
648
|
+
n: renderSessionNumber(current, markers),
|
|
649
|
+
title: label,
|
|
650
|
+
}));
|
|
651
|
+
}
|
|
652
|
+
return commandResult(t('当前会话:{title}', { title: label }));
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const sessionId = parsed.n !== null
|
|
656
|
+
? (ring ? sessionRingEntryByNumber(ring, parsed.n)?.sessionId : null)
|
|
657
|
+
: state?.sessionFor?.(key) ?? null;
|
|
658
|
+
if (parsed.n !== null && !sessionId) return unknownEntryResult(parsed.n);
|
|
659
|
+
if (!sessionId) {
|
|
660
|
+
// No binding yet: remember the title for the Session the next message makes.
|
|
661
|
+
await state?.setPendingTitle?.(key, parsed.title);
|
|
662
|
+
return commandResult(t('已记住新会话标题「{title}」,将在下一条消息创建会话时应用。', { title: parsed.title }));
|
|
663
|
+
}
|
|
664
|
+
try {
|
|
665
|
+
if (!(await renameSessionTitle(harness, key, sessionId, parsed.title))) {
|
|
666
|
+
return commandResult(t('当前 Harness 暂不支持重命名会话。'));
|
|
667
|
+
}
|
|
668
|
+
const entryNumber = parsed.n ?? (ring
|
|
669
|
+
? sessionRingEntryBySessionId(ring, sessionId)?.n ?? null
|
|
670
|
+
: null);
|
|
671
|
+
if (entryNumber !== null) {
|
|
672
|
+
await state?.renameSessionRing?.(key, entryNumber, parsed.title);
|
|
673
|
+
await state?.markSessionRingUserTitled?.(key, entryNumber);
|
|
674
|
+
}
|
|
675
|
+
return commandResult(t('已将会话标题改为「{title}」。', { title: parsed.title }));
|
|
676
|
+
} catch (error) {
|
|
677
|
+
return commandResult(t('暂时无法重命名会话,请稍后重试。'));
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function forkErrorMessage(error) {
|
|
682
|
+
const code = error?.code ?? error?.failure?.code;
|
|
683
|
+
if (code === 'session/fork-unavailable' || code === 'fork-unavailable') {
|
|
684
|
+
return t('当前会话还没有已完成的回合,无法分支。请先完成一个回合再 /fork。');
|
|
685
|
+
}
|
|
686
|
+
if (code === 'harness-api-not-found') {
|
|
687
|
+
return t('当前 Host 不支持会话分支(fork)。');
|
|
688
|
+
}
|
|
689
|
+
if (isSessionNotFound(code) || code === 'session-archived' || code === 'session-not-registered') {
|
|
690
|
+
return t('当前会话已不存在或已归档,无法分支。');
|
|
691
|
+
}
|
|
692
|
+
if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found') {
|
|
693
|
+
return t('工作区或机器人状态已发生变化,请重试 /fork。');
|
|
694
|
+
}
|
|
695
|
+
return t('暂时无法分支会话,请稍后重试。');
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function forkBindErrorMessage(error) {
|
|
699
|
+
const code = error?.code ?? error?.failure?.code;
|
|
700
|
+
if (isSessionNotFound(code) || code === 'session-archived' || code === 'session-not-registered') {
|
|
701
|
+
return t('分支出的子会话无法绑定,请重试。');
|
|
702
|
+
}
|
|
703
|
+
if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found') {
|
|
704
|
+
return t('工作区或机器人状态已发生变化,请重试 /fork。');
|
|
705
|
+
}
|
|
706
|
+
return t('暂时无法绑定分支出的子会话,请稍后重试。');
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
async function runFork(state, harness, key, rawTitle, { signal }) {
|
|
710
|
+
const parentId = state?.sessionFor?.(key);
|
|
711
|
+
if (!parentId) return commandResult(t('当前聊天尚未绑定会话。'));
|
|
712
|
+
if (typeof harness?.forkSession !== 'function') {
|
|
713
|
+
return commandResult(t('当前 Host 不支持会话分支(fork)。'));
|
|
714
|
+
}
|
|
715
|
+
// Refuse while the current turn is still running.
|
|
716
|
+
const session = typeof harness?.workspaceSession === 'function'
|
|
717
|
+
? harness.workspaceSession(parentId, key)
|
|
718
|
+
: null;
|
|
719
|
+
if (session && typeof session.isRunning === 'function') {
|
|
720
|
+
try {
|
|
721
|
+
if (await session.isRunning()) {
|
|
722
|
+
return commandResult(t('当前会话仍在生成回复,请先等待完成或发送 /stop 再分支。'));
|
|
723
|
+
}
|
|
724
|
+
} catch {
|
|
725
|
+
// A failed run-state check must not block the fork; the Host rechecks.
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
// Branch the Session.
|
|
729
|
+
let childId;
|
|
730
|
+
try {
|
|
731
|
+
const forked = await harness.forkSession(parentId, { signal });
|
|
732
|
+
childId = typeof forked === 'string' ? forked : forked?.sessionId;
|
|
733
|
+
if (typeof childId !== 'string' || !childId) {
|
|
734
|
+
throw Object.assign(new Error('fork returned no child session id'), { code: 'harness-response-invalid' });
|
|
735
|
+
}
|
|
736
|
+
} catch (error) {
|
|
737
|
+
if (error?.code === 'harness-response-invalid') return commandResult(t('暂时无法分支会话,请稍后重试。'));
|
|
738
|
+
return commandResult(forkErrorMessage(error));
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// Bind the child and register it in the ring.
|
|
742
|
+
try {
|
|
743
|
+
const bound = await harness.bindWorkspaceSession(key, childId);
|
|
744
|
+
if (bound?.archived === true) {
|
|
745
|
+
return commandResult(t('分支出的子会话已归档,无法绑定。'));
|
|
746
|
+
}
|
|
747
|
+
} catch (error) {
|
|
748
|
+
return commandResult(forkBindErrorMessage(error));
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// Title: the argument when given (user-titled), otherwise the parent title
|
|
752
|
+
// plus " (fork)", or the no-title form plus " (fork)".
|
|
753
|
+
const explicit = typeof rawTitle === 'string' && rawTitle;
|
|
754
|
+
const parentRing = state?.ringFor?.(key);
|
|
755
|
+
const parentEntry = parentRing ? sessionRingEntryBySessionId(parentRing, parentId) : null;
|
|
756
|
+
const title = explicit ? rawTitle : `${parentEntry?.title || t('无标题')} (fork)`;
|
|
757
|
+
|
|
758
|
+
const childRing = state?.ringFor?.(key);
|
|
759
|
+
const childEntry = childRing ? sessionRingEntryBySessionId(childRing, childId) : null;
|
|
760
|
+
if (!childEntry) return commandResult(t('分支出的子会话无法绑定,请重试。'));
|
|
761
|
+
|
|
762
|
+
// bindWorkspaceSession already appended the child as the current visit for a
|
|
763
|
+
// non-navigation bind; just rename and mark it here.
|
|
764
|
+
await renameSessionTitle(harness, key, childId, title);
|
|
765
|
+
await state?.renameSessionRing?.(key, childEntry.n, title);
|
|
766
|
+
if (explicit) await state?.markSessionRingUserTitled?.(key, childEntry.n);
|
|
767
|
+
|
|
768
|
+
const markers = await computeRingMarkers(state, harness, key, { signal });
|
|
769
|
+
const parentAvailability = parentEntry
|
|
770
|
+
? await entryAvailability(harness, key, parentEntry.sessionId, signal)
|
|
771
|
+
: 'alive';
|
|
772
|
+
return commandResult(t('已从会话 {parent} 分支到会话 {child}:{title}', {
|
|
773
|
+
parent: parentEntry ? renderSessionNumber(parentEntry, markers, parentAvailability) : '?',
|
|
774
|
+
child: renderSessionNumber(childEntry, markers),
|
|
775
|
+
title,
|
|
776
|
+
}));
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function parseTailArgument(raw) {
|
|
780
|
+
const tokens = (typeof raw === 'string' ? raw.trim() : '').split(/\s+/u).filter(Boolean);
|
|
781
|
+
let exportFile = false;
|
|
782
|
+
if (tokens.length > 0 && /^file$/iu.test(tokens[tokens.length - 1])) {
|
|
783
|
+
exportFile = true;
|
|
784
|
+
tokens.pop();
|
|
785
|
+
}
|
|
786
|
+
let n = null;
|
|
787
|
+
let count = null;
|
|
788
|
+
for (const token of tokens) {
|
|
789
|
+
if (!/^\d+$/u.test(token)) continue;
|
|
790
|
+
if (n === null) n = Number(token);
|
|
791
|
+
else if (count === null) count = Number(token);
|
|
792
|
+
}
|
|
793
|
+
return { n, count, exportFile };
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function resolveTailSession(state, key, n) {
|
|
797
|
+
if (n === null) {
|
|
798
|
+
const currentSessionId = state?.sessionFor?.(key) ?? null;
|
|
799
|
+
if (!currentSessionId) {
|
|
800
|
+
return { error: t('当前聊天尚未绑定会话,请先发送消息或使用 /session 绑定会话。') };
|
|
801
|
+
}
|
|
802
|
+
const ring = state?.ringFor?.(key);
|
|
803
|
+
const entry = ring ? sessionRingEntryBySessionId(ring, currentSessionId) : null;
|
|
804
|
+
return { sessionId: currentSessionId, n: entry?.n ?? null, title: entry?.title ?? null };
|
|
805
|
+
}
|
|
806
|
+
const ring = state?.ringFor?.(key);
|
|
807
|
+
const entry = ring ? sessionRingEntryByNumber(ring, n) : null;
|
|
808
|
+
if (!entry) return { error: t('没有编号为 {n} 的会话。用 /ls 查看列表。', { n }) };
|
|
809
|
+
return { sessionId: entry.sessionId, n: entry.n, title: entry.title ?? null };
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
async function runTailPreview(harness, key, resolved, count, { signal }) {
|
|
813
|
+
const session = harness?.workspaceSession?.(resolved.sessionId, key);
|
|
814
|
+
if (!session || typeof session.readHistory !== 'function') {
|
|
815
|
+
return commandResult(t('当前 Harness 暂不支持读取会话历史。'));
|
|
816
|
+
}
|
|
817
|
+
const { events, stopped } = await readTailEvents(session, {
|
|
818
|
+
signal,
|
|
819
|
+
stop: (acc) => tailMessages(sortedEvents(acc)).length >= count,
|
|
820
|
+
});
|
|
821
|
+
const messages = tailMessages(sortedEvents(events)).slice(-count);
|
|
822
|
+
if (messages.length === 0) {
|
|
823
|
+
return commandResult(stopped
|
|
824
|
+
? t('本次有限读取中未找到可预览的消息。')
|
|
825
|
+
: t('当前会话暂无可预览的消息。'));
|
|
826
|
+
}
|
|
827
|
+
return commandResult(renderTailPreview(messages, { count, n: resolved.n }), { hide: true });
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function exportFileName(title, n) {
|
|
831
|
+
const fallback = `session-${n ?? 'export'}`;
|
|
832
|
+
const base = (typeof title === 'string' && title.trim() ? title.trim() : fallback)
|
|
833
|
+
.replace(/[^\p{L}\p{N}\-_ ]/gu, '')
|
|
834
|
+
.replace(/\s+/gu, ' ')
|
|
835
|
+
.trim()
|
|
836
|
+
.slice(0, 60);
|
|
837
|
+
return `${base || fallback}.md`;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* The export header carries an untrusted title. Collapse every line break and
|
|
842
|
+
* control character to a single space so the title can never inject a heading
|
|
843
|
+
* or a fence line; whatever remains stays on the one `# …` header line.
|
|
844
|
+
*/
|
|
845
|
+
function sanitizeExportTitle(title) {
|
|
846
|
+
if (typeof title !== 'string') return null;
|
|
847
|
+
const cleaned = title
|
|
848
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, ' ')
|
|
849
|
+
.replace(/[\t\r\n]+/gu, ' ')
|
|
850
|
+
.replace(/[ \t]{2,}/gu, ' ')
|
|
851
|
+
.trim();
|
|
852
|
+
return cleaned || null;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Quote one message body verbatim inside a code fence whose delimiter is longer
|
|
857
|
+
* than any leading run of fence characters in the body, so the body can never
|
|
858
|
+
* close its own fence. The closing fence is always preceded by a newline.
|
|
859
|
+
*/
|
|
860
|
+
function fencedBody(body) {
|
|
861
|
+
const delimiter = safeCodeFence(body, '');
|
|
862
|
+
const padded = body.endsWith('\n') ? body : `${body}\n`;
|
|
863
|
+
return `${delimiter}\n${padded}${delimiter}`;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
function renderExport(messages, { title, n, truncated, exportedAt }) {
|
|
867
|
+
const safeTitle = sanitizeExportTitle(title);
|
|
868
|
+
// The skeleton is localized; message bodies stay verbatim inside fences, so a
|
|
869
|
+
// reader can always tell structure from data.
|
|
870
|
+
const headingParts = [];
|
|
871
|
+
if (safeTitle) headingParts.push(safeTitle);
|
|
872
|
+
if (n !== undefined && n !== null) headingParts.push(`${t('导出标题:会话')} ${n}`);
|
|
873
|
+
const heading = `# ${headingParts.join(' — ')}`.trimEnd();
|
|
874
|
+
const lines = [
|
|
875
|
+
heading,
|
|
876
|
+
'',
|
|
877
|
+
t('导出时间:{time}', { time: new Date(exportedAt).toISOString() }),
|
|
878
|
+
t('消息数:{count}', { count: messages.length }),
|
|
879
|
+
t('正文说明:消息正文以代码围栏逐字引用,围栏长度大于正文中任意连续的围栏字符。'),
|
|
880
|
+
...(truncated ? [t('注意:因事件数量达到上限,导出内容被截断。')] : []),
|
|
881
|
+
'',
|
|
882
|
+
];
|
|
883
|
+
for (const message of messages) {
|
|
884
|
+
const role = message.role === 'user' ? t('导出角色:用户') : t('导出角色:助手');
|
|
885
|
+
lines.push(`## ${role}`, '', fencedBody(message.text), '');
|
|
886
|
+
}
|
|
887
|
+
return lines.join('\n');
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
async function runTailExport(harness, key, resolved, { signal, eventCap }) {
|
|
891
|
+
const session = harness?.workspaceSession?.(resolved.sessionId, key);
|
|
892
|
+
if (!session || typeof session.readHistory !== 'function') {
|
|
893
|
+
return commandResult(t('当前 Harness 暂不支持读取会话历史。'));
|
|
894
|
+
}
|
|
895
|
+
const { events, stopped } = await readTailEvents(session, {
|
|
896
|
+
signal,
|
|
897
|
+
stop: (acc) => acc.size >= eventCap,
|
|
898
|
+
});
|
|
899
|
+
const messages = tailMessages(sortedEvents(events));
|
|
900
|
+
const content = renderExport(messages, {
|
|
901
|
+
title: resolved.title,
|
|
902
|
+
n: resolved.n,
|
|
903
|
+
truncated: stopped,
|
|
904
|
+
exportedAt: Date.now(),
|
|
905
|
+
});
|
|
906
|
+
return documentResult({
|
|
907
|
+
fileName: exportFileName(resolved.title, resolved.n),
|
|
908
|
+
mediaType: 'text/markdown',
|
|
909
|
+
content,
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
async function runTail(harness, state, key, parsed, { signal, eventCap }) {
|
|
914
|
+
const resolved = resolveTailSession(state, key, parsed.n);
|
|
915
|
+
if (resolved.error) return commandResult(resolved.error);
|
|
916
|
+
if (parsed.exportFile) return runTailExport(harness, key, resolved, { signal, eventCap });
|
|
917
|
+
const count = Math.min(Math.max(parsed.count ?? DEFAULT_TAIL_COUNT, 1), MAX_TAIL_COUNT);
|
|
918
|
+
return runTailPreview(harness, key, resolved, count, { signal });
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/**
|
|
922
|
+
* Handle one session-navigation command. Returns null when `text` is not one of
|
|
923
|
+
* them, otherwise a result the bridge can render as text, a document, or a
|
|
924
|
+
* button-carrying preview.
|
|
925
|
+
*/
|
|
926
|
+
export async function runSessionNavCommand(text, harness, state, key, options = {}) {
|
|
927
|
+
if (!isSessionNavCommand(text)) return null;
|
|
928
|
+
const command = text.trim();
|
|
929
|
+
const { signal } = options;
|
|
930
|
+
// The currently bound Session must always be listed; register it lazily if it
|
|
931
|
+
// predates the navigation ring.
|
|
932
|
+
await ensureCurrentSessionInRing(state, harness, key, { signal });
|
|
933
|
+
const tailOptions = {
|
|
934
|
+
signal,
|
|
935
|
+
eventCap: Number.isSafeInteger(options?.tailExportEventCap) && options.tailExportEventCap > 0
|
|
936
|
+
? options.tailExportEventCap
|
|
937
|
+
: TAIL_EXPORT_EVENT_CAP,
|
|
938
|
+
};
|
|
939
|
+
|
|
940
|
+
if (/^\/(?:ls|list)$/iu.test(command)) {
|
|
941
|
+
return runList(state, harness, key, { signal });
|
|
942
|
+
}
|
|
943
|
+
if (/^\/go$/iu.test(command)) {
|
|
944
|
+
return commandResult(t('用法:/go 会话编号(用 /ls 查看编号)。'));
|
|
945
|
+
}
|
|
946
|
+
const goMatch = GO_COMMAND.exec(command);
|
|
947
|
+
if (goMatch) {
|
|
948
|
+
const n = Number(goMatch[1]);
|
|
949
|
+
if (!Number.isSafeInteger(n) || n < 1) return commandResult(t('用法:/go 会话编号(用 /ls 查看编号)。'));
|
|
950
|
+
return runGo(state, harness, key, n, { signal, askText: goMatch[2] ?? null });
|
|
951
|
+
}
|
|
952
|
+
const prevMatch = PREV_COMMAND.exec(command);
|
|
953
|
+
if (prevMatch) return runStep(state, harness, key, 'back', { signal, askText: prevMatch[1] ?? null });
|
|
954
|
+
const nextMatch = NEXT_COMMAND.exec(command);
|
|
955
|
+
if (nextMatch) return runStep(state, harness, key, 'forward', { signal, askText: nextMatch[1] ?? null });
|
|
956
|
+
const dropMatch = DROP_COMMAND.exec(command);
|
|
957
|
+
if (dropMatch) {
|
|
958
|
+
if (dropMatch[1] === 'all' || dropMatch[1] === '*') {
|
|
959
|
+
return runDropAll(state, key);
|
|
960
|
+
}
|
|
961
|
+
const n = Number(dropMatch[1]);
|
|
962
|
+
if (!Number.isSafeInteger(n) || n < 1) return commandResult(t('用法:/drop 会话编号(用 /ls 查看编号)。'));
|
|
963
|
+
return runDrop(state, harness, key, n, { signal });
|
|
964
|
+
}
|
|
965
|
+
const titleMatch = TITLE_COMMAND.exec(command);
|
|
966
|
+
if (titleMatch) return runTitle(state, harness, key, titleMatch[1] ?? '', { signal });
|
|
967
|
+
const forkMatch = FORK_COMMAND.exec(command);
|
|
968
|
+
if (forkMatch) {
|
|
969
|
+
const rawTitle = typeof forkMatch[1] === 'string' && forkMatch[1].trim()
|
|
970
|
+
? normalizeSessionTitle(forkMatch[1])
|
|
971
|
+
: null;
|
|
972
|
+
return runFork(state, harness, key, rawTitle, { signal });
|
|
973
|
+
}
|
|
974
|
+
const tailMatch = TAIL_COMMAND.exec(command);
|
|
975
|
+
if (tailMatch) {
|
|
976
|
+
try {
|
|
977
|
+
return await runTail(harness, state, key, parseTailArgument(tailMatch[1] ?? ''), tailOptions);
|
|
978
|
+
} catch (error) {
|
|
979
|
+
return commandResult(tailErrorMessage(error));
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
return commandResult(t('未知命令,请发送 /help 查看帮助。'));
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/**
|
|
986
|
+
* Text-only seam for bridges without document or button support. Detects a
|
|
987
|
+
* session-navigation command, dispatches to the shared logic, and degrades a
|
|
988
|
+
* file export to an honest "files unavailable" reply, so the caller only ever
|
|
989
|
+
* sends text.
|
|
990
|
+
*/
|
|
991
|
+
export async function runSessionNavTextCommand(text, harness, state, key, options = {}) {
|
|
992
|
+
const result = await runSessionNavCommand(text, harness, state, key, options);
|
|
993
|
+
if (!result) return null;
|
|
994
|
+
if (result.document) {
|
|
995
|
+
const message = t('当前渠道不支持发送文件。');
|
|
996
|
+
return { handled: true, message, messages: splitWorkspaceCommandMessage(message) };
|
|
997
|
+
}
|
|
998
|
+
return { handled: true, message: result.message, messages: result.messages, askText: result.askText };
|
|
999
|
+
}
|