@ryuu-64/dsh-session-tools 0.7.0 → 0.8.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.md CHANGED
@@ -4,6 +4,22 @@
4
4
 
5
5
  适合把独立的调查或整理工作交给另一个会话,省去手动新建、复制背景、来回转述。新会话会出现在侧边栏,你可以随时打开,直接继续对话。
6
6
 
7
+ ## 会话通信
8
+
9
+ `0.8.0` 增加会话通信开关和原生右侧栏入口,并保留 `0.7.0` 的会话发现与消息回执功能。兼容范围与宿主要求见[兼容说明](https://github.com/Ryuu-64/dsh-session-tools/blob/main/docs/compatibility.md)。
10
+
11
+ 打开当前对话右侧的「会话」tab,顶部可分别控制「接收其他会话消息」和「向其他会话发送」,下方保留相关对话。没有相关对话时,顶部会话入口仍可使用。左侧会话「…」菜单中的「会话通信…」也保留,与右栏使用同一状态和保存逻辑。开关保存成功后立即生效;保存失败或结果不明时不会显示已保存。两个页面同时修改时会提示冲突,并显示最新设置。同一窗口的多个入口立即同步;其他窗口通过可见页面每 3 秒一次的权威重读同步(另加请求耗时,不是实时订阅),打开面板、切换会话、恢复焦点或页面可见性时也会重读。相同会话的请求去重,保存时暂停常规刷新;读取失败显示未知并可重试。保存超过 12 秒时先提示结果尚未确认并重读,原请求未结束前禁止重复提交,不伪造回滚。
12
+
13
+ 关闭发送也会阻止创建带首条消息的新会话。关闭只拒绝之后的新消息,不取消已经接收的工作,也不影响历史读取。完全访问权限不会绕过这两个开关。没有保存过设置的会话默认开启两项;损坏或无法读取的权限记录会拒绝新的投递。
14
+
15
+ 这是本插件的通信控制,不是宿主安全隔离。修改入口使用宿主认证的 Remote,不注册给模型使用的权限设置工具;但宿主 operator 身份不能证明是人亲自点击,也不能阻止同进程的高权限代码调用宿主或修改文件。
16
+
17
+ ### 发送前查看与发送后回执
18
+
19
+ 找会话时,`list_sessions` 会顺带显示当前调用方到目标的发送/接收开关状态;每页从权威存储重新读取。正常发送不必额外查询一次。只想检查某个已知目标是否恢复接收时,可按需调用只读 `session_communication_status`;未知、不可访问或无法确认的目标不会显示默认允许。
20
+
21
+ 查询只是当时的开关快照,不是审批或已送达承诺。`session_send` 在实际投递前仍重检;拒收保持错误结果,明确未送达、未排队,没有消息回执。成功投递后继续用 `messageId` 和 `session_wait` 查具体消息:已排队、已交给目标与本轮结束是不同状态,本轮结束不等于任务成功。不自动重试、补送或订阅开关变更,也不结束发送方整轮。
22
+
7
23
  ## 安装
8
24
 
9
25
  需要已能正常使用的 DSH 和模型配置,以及 **Node.js 22.19+(22 系列)或 24.x**。`dsh plugin` 使用 pnpm 管理插件;请确保它在命令行中可用。
@@ -13,10 +29,10 @@
13
29
  在终端中安装到你使用的宿主配置(profile),下面以 `web` 为例:
14
30
 
15
31
  ```sh
16
- dsh plugin --profile web add @ryuu-64/dsh-session-tools@0.7.0
32
+ dsh plugin --profile web add @ryuu-64/dsh-session-tools@0.8.0
17
33
  ```
18
34
 
19
- 安装后重启对应的 DSH 宿主。插件没有额外配置项;自定义宿主配置还需满足[服务要求](https://github.com/Ryuu-64/dsh-session-tools/blob/main/docs/compatibility.md)。
35
+ 安装后重启对应的 DSH 宿主。插件没有额外全局配置项;自定义宿主配置还需满足[服务要求](https://github.com/Ryuu-64/dsh-session-tools/blob/main/docs/compatibility.md)。
20
36
 
21
37
  ## 开始使用
22
38
 
@@ -46,6 +62,7 @@ dsh plugin --profile web add @ryuu-64/dsh-session-tools@0.7.0
46
62
  | 给另一个普通会话发送新消息 | `session_send` |
47
63
  | 按标题或工作区筛选、按最近活动分页列出会话 | `list_sessions` |
48
64
  | 查询某次消息的结果,或查看会话概况 | `session_wait` |
65
+ | 按需检查已知目标的当前通信开关 | `session_communication_status` |
49
66
 
50
67
  创建时可指定标题;不指定时,从首条任务生成固定标题,不额外调用模型。之后你仍可手动改名。
51
68
 
package/lib/client.js CHANGED
@@ -14,6 +14,7 @@ window.__ModuleLoader__.load({
14
14
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
15
15
 
16
16
  const react = require("react");
17
+ const { MenuItemButton, Modal, Button, Switch, ReferenceIconRegular } = require("@deepseek-ai/dsh-client-ui-primitives");
17
18
 
18
19
  /** Slots this client half needs before it can register anything. */
19
20
  const inject = ["slots", "sessions"];
@@ -107,16 +108,397 @@ window.__ModuleLoader__.load({
107
108
  title,
108
109
  ),
109
110
  react.createElement("span", { style: { opacity: 0.55, fontFamily: "ui-monospace, monospace", fontSize: "11px" } }, created.sessionId),
111
+ react.createElement("div", { style: { flexBasis: "100%" } }, react.createElement(MessageStateRow, { block: props.block })),
110
112
  );
111
113
  }
112
114
 
115
+
116
+ const statusLabels = {
117
+ queued: "已排队", delivered: "已交给目标", turnCompleted: "目标本轮结束(不等于任务成功)",
118
+ discarded: "取消", cancelled: "取消", interrupted: "中断", failed: "失败", incomplete: "未完整结束",
119
+ blocked: "未完整结束", unknown: "暂无法确认",
120
+ };
121
+ function MessageStateRow({ block }) {
122
+ const text = resultText(block);
123
+ if (block?.kind !== "tool-result") return react.createElement("span", { role: "status" }, "正在处理…");
124
+ const meta = block.meta;
125
+ if (block.isError || meta?.scope === "sessionOverview" || typeof meta?.messageId !== "string") {
126
+ return react.createElement("div", { style: { whiteSpace: "pre-wrap", overflowWrap: "anywhere" } }, text || "暂无法确认");
127
+ }
128
+ return react.createElement("div", { style: { display: "grid", gap: 6 } },
129
+ react.createElement("strong", null, statusLabels[meta.messageStatus] ?? "暂无法确认"),
130
+ meta.waitStatus === "timedOut" && react.createElement("div", null, "等待超时。没有重发,也没有取消;请用同一消息编号继续查询。"),
131
+ meta.waitStatus === "callerCancelled" && react.createElement("div", null, "已停止等待,目标会话继续处理。"),
132
+ react.createElement("details", null, react.createElement("summary", null, "消息编号与结果详情"),
133
+ react.createElement("div", { style: { whiteSpace: "pre-wrap", overflowWrap: "anywhere", color: "var(--dsw-alias-label-secondary)" } }, text)));
134
+ }
135
+ const remoteContribution = (() => {
136
+ // TypertSchema requires parse(value); keep these strict schemas local to
137
+ // this browser bundle because Zod is not a platform module seed.
138
+ const scalar = check => value => {
139
+ if (!check(value)) throw new TypeError("Invalid session communication field");
140
+ return value;
141
+ };
142
+ const object = fields => ({ parse(value) {
143
+ if (!value || typeof value !== "object" || Array.isArray(value)
144
+ || Object.keys(value).some(key => !Object.hasOwn(fields, key))
145
+ || Object.keys(fields).some(key => !Object.hasOwn(value, key))) {
146
+ throw new TypeError("Invalid session communication object");
147
+ }
148
+ return Object.fromEntries(Object.entries(fields).map(([key, parse]) => [key, parse(value[key])]));
149
+ } });
150
+ const sessionId = scalar(value => typeof value === "string" && value.length >= 1 && value.length <= 1024);
151
+ const boolean = scalar(value => typeof value === "boolean");
152
+ const revision = scalar(value => Number.isSafeInteger(value) && value >= 0);
153
+ const getSchema = object({ sessionId });
154
+ const setSchema = object({ sessionId, send: boolean, receive: boolean, expectedRevision: revision });
155
+ const recordSchema = object({ send: boolean, receive: boolean, revision });
156
+ const setResultSchema = object({ status: scalar(value => value === "saved" || value === "conflict"), current: value => recordSchema.parse(value) });
157
+ return {
158
+ package: "@ryuu-64/dsh-session-tools",
159
+ descriptors: ["get", "set"].map(method => ({
160
+ id: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}`,
161
+ service: "sessionCommunication", namespace: "sessionCommunication", method,
162
+ invocation: { kind: "direct" },
163
+ parameters: [{ name: "request", wire: "request", source: "json", codec: {
164
+ mode: "strict", typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:request`,
165
+ create: () => method === "get" ? getSchema : setSchema,
166
+ } }],
167
+ result: {
168
+ mode: "strict", typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:result`,
169
+ create: () => method === "get" ? recordSchema : setResultSchema,
170
+ },
171
+ })),
172
+ };
173
+ })();
174
+ function validRecord(value) {
175
+ return value && typeof value.send === "boolean" && typeof value.receive === "boolean" && Number.isSafeInteger(value.revision) && value.revision >= 0;
176
+ }
177
+ // One authoritative cache per client, shared by every pane and the menu.
178
+ // Other windows are reconciled by bounded polling and focus/visibility reads.
179
+ function createCommunicationStore() {
180
+ let api;
181
+ const entries = new Map();
182
+ const entryFor = id => {
183
+ if (!entries.has(id)) entries.set(id, { listeners: new Set(), active: 0, token: 0, reading: false, saving: false,
184
+ value: { record: null, busy: false, failed: false, notice: "正在读取设置…" } });
185
+ return entries.get(id);
186
+ };
187
+ const publish = (entry, patch) => {
188
+ entry.value = { ...entry.value, ...patch };
189
+ entry.listeners.forEach(listener => listener());
190
+ };
191
+ const read = async (id, verifyPending = false) => {
192
+ const entry = entryFor(id);
193
+ if (!api || entry.reading || (entry.saving && !verifyPending)) return;
194
+ entry.reading = true;
195
+ if (!entry.value.record) publish(entry, { busy: true });
196
+ const token = ++entry.token;
197
+ let timer;
198
+ try {
199
+ const result = await Promise.race([api.get({ sessionId: id }), new Promise((_, reject) => {
200
+ timer = setTimeout(() => reject(new Error("read timeout")), 12000);
201
+ })]);
202
+ if (token !== entry.token) return;
203
+ if (!result.ok || !validRecord(result.value)) throw new Error("unavailable");
204
+ if (entry.value.record && result.value.revision < entry.value.record.revision) return;
205
+ const changed = entry.value.record && result.value.revision !== entry.value.record.revision;
206
+ publish(entry, { record: result.value, failed: changed ? false : !!entry.value.record && entry.value.failed,
207
+ notice: entry.saving ? "已读取当前设置,保存请求仍未结束;暂不能再次更改。" : changed ? "设置已在其他页面更改,已同步最新状态。" : entry.value.record ? entry.value.notice : "已读取最新设置。更改后立即生效。" });
208
+ } catch {
209
+ if (token === entry.token) publish(entry, { record: null, failed: true, notice: "状态未知,暂时无法读取设置。请重试。" });
210
+ } finally {
211
+ clearTimeout(timer); entry.reading = false;
212
+ if (token === entry.token) publish(entry, { busy: entry.saving });
213
+ if (!entry.listeners.size && !entry.saving) entries.delete(id);
214
+ }
215
+ };
216
+ const change = async (id, key, next) => {
217
+ const entry = entryFor(id), record = entry.value.record;
218
+ if (!api || !record || entry.saving) return;
219
+ const owner = api;
220
+ entry.saving = true; ++entry.token;
221
+ publish(entry, { busy: true, failed: false, notice: "正在保存…" });
222
+ // A timeout cannot cancel an accepted write. Keep the write lock until
223
+ // it settles; never replay it or offer a misleading rollback.
224
+ let timedOut = false, staleResponse = false;
225
+ const timer = setTimeout(() => {
226
+ if (api !== owner) return;
227
+ timedOut = true;
228
+ publish(entry, { record: null, failed: true, notice: "保存结果尚未确认,仍在等待。不会重复提交;关闭面板不会取消更改。" });
229
+ void read(id, true);
230
+ }, 12000);
231
+ try {
232
+ const result = await owner.set({ sessionId: id, send: record.send, receive: record.receive, [key]: next, expectedRevision: record.revision });
233
+ if (api !== owner) return;
234
+ if (!result.ok || !validRecord(result.value?.current) || !["saved", "conflict"].includes(result.value?.status)) throw new Error("unconfirmed");
235
+ if (entry.value.record && result.value.current.revision < entry.value.record.revision) { staleResponse = true; return; }
236
+ publish(entry, { record: result.value.current, failed: result.value.status === "conflict",
237
+ notice: result.value.status === "saved" ? "已保存,立即生效。" : "设置已在其他页面更改。已显示最新设置,请确认后再操作。" });
238
+ } catch {
239
+ if (api !== owner) return;
240
+ publish(entry, { record: null, failed: true, notice: "保存结果暂无法确认,正在重新读取;不会自动重复保存。" });
241
+ } finally {
242
+ clearTimeout(timer); ++entry.token; entry.saving = false; publish(entry, { busy: false });
243
+ if (api !== owner || timedOut || staleResponse || !entry.value.record) void read(id);
244
+ else if (!entry.listeners.size && !entry.reading) entries.delete(id);
245
+ }
246
+ };
247
+ const refresh = () => { if (document.visibilityState === "hidden") return; for (const [id, entry] of entries) if (entry.active) void read(id); };
248
+ return {
249
+ connect(value) {
250
+ api = value; refresh();
251
+ return () => {
252
+ if (api !== value) return;
253
+ api = undefined;
254
+ for (const entry of entries.values()) {
255
+ ++entry.token;
256
+ publish(entry, { record: null, busy: entry.saving, failed: true, notice: "连接已断开,状态未知。恢复连接后会重新读取。" });
257
+ }
258
+ };
259
+ },
260
+ get: id => entryFor(id).value, read, change,
261
+ subscribe(id, listener, active) {
262
+ const entry = entryFor(id); entry.listeners.add(listener);
263
+ if (active) entry.active++;
264
+ if (active && entry.active === 1) {
265
+ entry.timer = setInterval(() => { if (document.visibilityState !== "hidden") void read(id); }, 3000);
266
+ window.addEventListener("focus", refresh);
267
+ document.addEventListener("visibilitychange", refresh);
268
+ }
269
+ if (active) void read(id);
270
+ return () => {
271
+ entry.listeners.delete(listener);
272
+ if (active) entry.active--;
273
+ if (!entry.active) clearInterval(entry.timer);
274
+ if (![...entries.values()].some(item => item.active)) {
275
+ window.removeEventListener("focus", refresh); document.removeEventListener("visibilitychange", refresh);
276
+ }
277
+ if (!entry.listeners.size && !entry.reading && !entry.saving) entries.delete(id);
278
+ };
279
+ },
280
+ };
281
+ }
282
+ function CommunicationControls({ sessionId, store, compact = false, visible = true }) {
283
+ const subscribe = react.useCallback(listener => store.subscribe(sessionId, listener, visible), [store, sessionId, visible]);
284
+ const snapshot = react.useCallback(() => store.get(sessionId), [store, sessionId]);
285
+ const { record, busy, failed, notice } = react.useSyncExternalStore(subscribe, snapshot);
286
+ react.useEffect(() => { if (visible) void store.read(sessionId); }, [store, sessionId, visible]);
287
+ const row = (key, label, description) => react.createElement("div", { key, style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: compact ? 8 : 24, padding: compact ? "10px 0" : "16px 0", borderBottom: "0.5px solid var(--dsw-alias-border-l2)" } },
288
+ react.createElement("div", { title: description, style: { flex: 1, minWidth: 0, fontSize: compact ? 13 : 14, lineHeight: "20px", color: "var(--dsw-alias-label-primary)" } }, label,
289
+ !compact && react.createElement("div", { style: { marginTop: 4, fontSize: 12, lineHeight: "18px", color: "var(--dsw-alias-label-secondary)" } }, description)),
290
+ react.createElement("span", { "aria-hidden": true, style: { flexShrink: 0, color: "var(--dsw-alias-label-secondary)", fontSize: 12 } }, record ? record[key] ? "开启" : "关闭" : "未知"),
291
+ record && react.createElement(Switch, { checked: record[key], onChange: value => void store.change(sessionId, key, value), label, disabled: busy }));
292
+ return react.createElement("section", { "aria-label": "会话通信", "aria-busy": busy, "data-communication-session": sessionId, style: { padding: compact ? "0 6px 12px" : 0, minWidth: 0 } },
293
+ row("receive", "接收其他会话消息", "关闭会拒绝新的插件消息:未送达、未排队;已接收消息继续处理。"),
294
+ row("send", "向其他会话发送", "也控制创建带首条消息的新会话。"),
295
+ (!compact || record?.receive === false) && react.createElement("p", { style: { color: "var(--dsw-alias-label-secondary)", fontSize: 12, lineHeight: "18px" } }, "仅控制本插件的新消息。关闭接收后,新消息未送达、未排队;已经接收的消息继续处理,历史仍可查看。"),
296
+ react.createElement("div", { role: failed ? "alert" : "status", "aria-live": "polite", style: { marginTop: 8, fontSize: 12, lineHeight: "18px", color: failed ? "var(--dsw-alias-state-error-primary)" : "var(--dsw-alias-label-secondary)" } }, notice),
297
+ !record && !busy && react.createElement(Button, { variant: "outline", onClick: () => void store.read(sessionId) }, "重新读取"));
298
+ }
299
+ function CommunicationForm({ request, store, close }) {
300
+ return react.createElement(Modal, { open: true, onClose: close, closeLabel: "关闭", title: "会话通信", description: request.title || request.sessionId,
301
+ footer: react.createElement(Button, { variant: "outline", onClick: close }, "关闭"),
302
+ }, react.createElement(CommunicationControls, { sessionId: request.sessionId, store }));
303
+ }
304
+ /** Direct ordinary children from the public, durable host catalog.
305
+ * The client controller maps header.parentSession to summary.parentId.
306
+ * Never infer lineage from workspace, title or message text. Native
307
+ * subagents keep their existing catalog and continuation semantics.
308
+ */
309
+ function RelatedConversationRows({ sessionId, useSessions, useWorkspaces, openSession }) {
310
+ const catalog = useSessions(state => state);
311
+ const workspaces = useWorkspaces(state => state);
312
+ const [expandedSession, setExpandedSession] = react.useState(null);
313
+ const expanded = expandedSession === sessionId;
314
+ const scrollRegion = react.useRef(null);
315
+ const firstAdded = react.useRef(null);
316
+ const expansion = react.useRef(null);
317
+ react.useLayoutEffect(() => {
318
+ const pending = expansion.current, region = scrollRegion.current;
319
+ if (!expanded || !pending || !region) return;
320
+ expansion.current = null;
321
+ region.scrollTop = pending.scrollTop;
322
+ if (pending.keyboard && firstAdded.current) {
323
+ firstAdded.current.focus({ preventScroll: true });
324
+ const item = firstAdded.current.getBoundingClientRect(), bounds = region.getBoundingClientRect();
325
+ if (item.height > bounds.height) region.scrollTop += item.top - bounds.top;
326
+ else if (item.bottom > bounds.bottom) region.scrollTop += item.bottom - bounds.bottom;
327
+ else if (item.top < bounds.top) region.scrollTop -= bounds.top - item.top;
328
+ }
329
+ }, [expanded]);
330
+ // Identity order is stable across activity/title updates and remounts.
331
+ const children = catalog.ids.map(id => catalog.byId[id]).filter(row =>
332
+ row && row.id !== sessionId && row.parentId === sessionId && row.origin !== "subagent" && !workspaces.archivedSessionIds.includes(row.id))
333
+ .sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
334
+ const parentId = catalog.byId[sessionId]?.parentId;
335
+ const parent = parentId && parentId !== sessionId ? catalog.byId[parentId] : null;
336
+ const workspaceOf = id => workspaces.items.find(item => item.sessionIds.includes(id));
337
+ const currentWorkspace = workspaceOf(sessionId);
338
+ const titleOf = row => row.title?.trim() ? row.title : row.id;
339
+ const visible = expanded ? children : children.slice(0, 3);
340
+ const listId = "session-tools-children-" + sessionId;
341
+ if ((!parentId || parentId === sessionId) && children.length === 0) return react.createElement("p", { style: { margin: 8, color: "var(--dsw-alias-label-secondary)", fontSize: 13 } }, "当前对话还没有相关对话。");
342
+ return react.createElement("section", {
343
+ "aria-label": "相关对话", ref: scrollRegion,
344
+ style: { padding: "4px 6px 6px", minWidth: 0, minHeight: 0, overflowY: "auto" },
345
+ },
346
+ parentId && parentId !== sessionId ? react.createElement(Button, {
347
+ variant: "ghost", disabled: workspaces.archivedSessionIds.includes(parentId), onClick: () => openSession(parentId),
348
+ style: { width: "100%", justifyContent: "flex-start", height: "auto", padding: "6px 8px", textAlign: "left", whiteSpace: "normal", overflowWrap: "anywhere" },
349
+ }, (workspaces.archivedSessionIds.includes(parentId) ? "父对话已归档 · " : "返回父对话 · ") + (parent ? titleOf(parent) : parentId)) : null,
350
+ children.length ? react.createElement(react.Fragment, null,
351
+ react.createElement("div", { style: { padding: "2px 8px", fontSize: 12, lineHeight: "18px", color: "var(--dsw-alias-label-secondary)" } }, "创建的对话 · " + children.length),
352
+ react.createElement("div", { id: listId }, visible.map((child, index) => {
353
+ const workspace = workspaceOf(child.id);
354
+ const crossWorkspace = workspaces.phase === "ready" && workspaces.state !== "error" && workspace?.workspaceId !== currentWorkspace?.workspaceId;
355
+ return react.createElement(Button, {
356
+ key: child.id, ref: index === 3 ? firstAdded : undefined, variant: "ghost", title: child.id, onClick: () => openSession(child.id),
357
+ style: { width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "6px 8px", height: "auto", minWidth: 0, textAlign: "left" },
358
+ },
359
+ react.createElement("span", { style: { minWidth: 0, overflowWrap: "anywhere", whiteSpace: "normal", fontSize: 13, lineHeight: "20px" } },
360
+ titleOf(child),
361
+ crossWorkspace ? react.createElement("span", { style: { display: "block", fontSize: 11, color: "var(--dsw-alias-label-secondary)" } }, "跨工作区 · " + (workspace?.title || workspace?.path || "未分组")) : null),
362
+ react.createElement("span", { style: { flexShrink: 0, color: "var(--dsw-alias-label-secondary)", fontSize: 12 } }, child.running === true ? "运行中" : child.running === false ? "空闲" : "状态未知"));
363
+ })),
364
+ children.length > 3 ? react.createElement(Button, {
365
+ variant: "ghost", "aria-expanded": expanded, "aria-controls": listId,
366
+ onClick: event => {
367
+ expansion.current = expanded ? null : { keyboard: event.detail === 0, scrollTop: scrollRegion.current?.scrollTop || 0 };
368
+ setExpandedSession(expanded ? null : sessionId);
369
+ },
370
+ style: { width: "100%", fontSize: 12, height: "auto", padding: "6px 8px" },
371
+ }, expanded ? "收起列表" : "展开更多(" + (children.length - 3) + ")") : null) : null);
372
+ }
373
+
374
+ const RELATIONS_TAB = "@ryuu-64/dsh-session-tools/relations";
375
+ const RELATIONS_KIND = "session-tools.relations";
376
+ // Only the automatic first reveal is plugin-owned. All pane geometry,
377
+ // collapse, movement, docking and layout persistence belong to DSH.
378
+ function hasRelations(sessionId, catalog, workspaces) {
379
+ const archived = workspaces.archivedSessionIds;
380
+ const parentId = catalog.byId[sessionId]?.parentId;
381
+ return (!!parentId && parentId !== sessionId && !!catalog.byId[parentId] && !archived.includes(parentId)) ||
382
+ catalog.ids.some(id => {
383
+ const row = catalog.byId[id];
384
+ return row && id !== sessionId && row.parentId === sessionId && row.origin !== "subagent" && !archived.includes(id);
385
+ });
386
+ }
387
+ function RelationsTab(props) {
388
+ const { tab } = props.useTabInfo();
389
+ react.useLayoutEffect(() => {
390
+ props.visibility.set(tab.id, tab.visible);
391
+ return () => props.visibility.delete(tab.id);
392
+ }, [props.visibility, tab.id, tab.visible]);
393
+ return react.createElement("div", {
394
+ "data-session-tools-tab": props.sessionId,
395
+ style: { height: "100%", minHeight: 0, overflow: "auto", padding: 8, boxSizing: "border-box" },
396
+ }, react.createElement(CommunicationControls, { key: props.sessionId, sessionId: props.sessionId, store: props.communication, compact: true, visible: tab.visible }),
397
+ react.createElement(RelatedConversationRows, { ...props, key: tab.id }));
398
+ }
399
+ function RelationsEntry(props) {
400
+ const catalog = props.useSessions(state => state);
401
+ const workspaces = props.useWorkspaces(state => state);
402
+ const mounted = react.useSyncExternalStore(props.sidebar?.mounted.subscribe ?? (() => () => {}), props.sidebar?.mounted.getSnapshot ?? (() => undefined));
403
+ const available = workspaces.phase === "ready" && hasRelations(props.sessionId, catalog, workspaces);
404
+ react.useEffect(() => {
405
+ if (!props.sidebar || !available || mounted !== props.sessionId || props.wasShown(props.sessionId)) return;
406
+ // This is synchronous and rechecks the host's owner before opening.
407
+ // Record success only after the native tab actually exists.
408
+ props.reveal(props.sessionId, true);
409
+ }, [available, mounted, props.sessionId, props.reveal, props.wasShown]);
410
+ if (!props.sessionId) return null;
411
+ return react.createElement(Button, {
412
+ variant: "ghost", size: "sm", title: props.sidebar ? "会话通信与相关对话" : "会话工具不可用:宿主未提供会话工具停靠接口", "aria-label": props.sidebar ? "会话通信与相关对话" : "会话工具不可用:宿主未提供会话工具停靠接口", disabled: !props.sidebar,
413
+ style: { flex: "none", width: 28, padding: 0, color: "var(--dsw-alias-label-secondary)" },
414
+ onClick: () => props.reveal(props.sessionId, false),
415
+ }, react.createElement(ReferenceIconRegular, { kind: "session", size: 16 }));
416
+ }
417
+ function registerCommunicationUI(ctx, store) {
418
+ let request = null;
419
+ const listeners = new Set();
420
+ const publish = value => { request = value; for (const listener of listeners) listener(); };
421
+ const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener); };
422
+ function Overlay() {
423
+ const current = react.useSyncExternalStore(subscribe, () => request);
424
+ return current ? react.createElement(CommunicationForm, { key: current.sessionId, request: current, store, close: () => publish(null) }) : null;
425
+ }
426
+ ctx.slots.inject("shell.overlay", () => ctx.slots.register({ name: "shell.overlay", id: "session-tools.communication" }, Overlay));
427
+ ctx.slots.inject("sidebar.workspaces.session.menu.item", () => ctx.slots.register({ name: "sidebar.workspaces.session.menu.item", id: "session-tools.communication", order: 350 },
428
+ ({ sessionId, displayTitle, useMenuOpenState }) => {
429
+ const [, setMenuOpen] = useMenuOpenState();
430
+ return react.createElement(MenuItemButton, { onSelect: () => { setMenuOpen(false); publish({ sessionId, title: displayTitle }); } }, "会话通信…");
431
+ }));
432
+ }
433
+
113
434
  /**
114
435
  * Wait for the tool view slot list to exist, then register a keyed row that
115
436
  * replaces the default card for `session_create`.
116
437
  * @param ctx - the browser plugin context.
117
438
  */
118
439
  function apply(ctx) {
119
- const register = (scope, openSession) => scope.slots.inject("tool.call.toolview", () => scope.slots.register(
440
+ const communication = createCommunicationStore();
441
+ ctx.inject(["remote"], async scope => {
442
+ try {
443
+ await scope.remote.$mount(remoteContribution);
444
+ scope.inject(["remote.sessionCommunication"], ui => {
445
+ ui.effect(() => communication.connect(ui.remote.sessionCommunication));
446
+ registerCommunicationUI(ui, communication);
447
+ });
448
+ } catch(error) { console.error("[session-tools] communication UI initialization failed", error); throw error; }
449
+ });
450
+ ctx.slots.inject("tool.call.toolview", function* () {
451
+ for (const key of ["session_send", "session_wait"]) yield ctx.slots.register({ name: "tool.call.toolview", key }, MessageStateRow);
452
+ });
453
+ const register = (scope, openSession) => {
454
+ let capabilities = {};
455
+ const listeners = new Set();
456
+ const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener); };
457
+ const snapshot = () => capabilities;
458
+ scope.slots.inject("conversation.session.header.utilities", () => scope.slots.register({
459
+ name: "conversation.session.header.utilities", id: "session-tools.relations",
460
+ }, props => react.createElement(RelationsEntry, { ...props, ...react.useSyncExternalStore(subscribe, snapshot) })));
461
+ scope.inject(["sidebarRight", "sidebarRightTabs"], ui => {
462
+ const sidebar = ui.sidebarRight;
463
+ if (!["openTab", "tabsIn", "focus"].every(key => typeof sidebar[key] === "function") || typeof sidebar.mounted?.getSnapshot !== "function" || typeof sidebar.mounted?.subscribe !== "function" || typeof sidebar.tabDomain?.occurrence !== "function" || typeof ui.sidebarRightTabs.register !== "function") return;
464
+ const shown = new Set(), visibility = new Map();
465
+ const storageKey = id => "dsh-session-tools:relations-shown:" + id;
466
+ const wasShown = id => {
467
+ if (shown.has(id)) return true;
468
+ try { return localStorage.getItem(storageKey(id)) === "1"; } catch { return false; }
469
+ };
470
+ const markShown = id => {
471
+ shown.add(id);
472
+ try { localStorage.setItem(storageKey(id), "1"); } catch { /* In-memory suppression still respects a close this run. */ }
473
+ };
474
+ const reveal = (id, automatic) => {
475
+ if (ui.sidebarRight.mounted.getSnapshot() !== id) return;
476
+ const existing = ui.sidebarRight.tabsIn(id).find(tab => tab.kind === RELATIONS_KIND);
477
+ if (existing) {
478
+ // A restored layout must keep the user's selected tab and collapsed state.
479
+ if (!automatic) {
480
+ const occurrence = sidebar.tabDomain.occurrence(id, { id: existing.id });
481
+ if (typeof sidebar.revealOccurrence === "function") sidebar.revealOccurrence(occurrence);
482
+ else if (visibility.get(existing.id)) sidebar.focus(existing.id);
483
+ else occurrence.tabActions.openTab(RELATIONS_KIND);
484
+ }
485
+ } else ui.sidebarRight.openTab(RELATIONS_KIND);
486
+ if (ui.sidebarRight.tabsIn(id).some(tab => tab.kind === RELATIONS_KIND)) markShown(id);
487
+ };
488
+ ui.effect(() => ui.sidebarRightTabs.register({
489
+ id: RELATIONS_TAB, kind: RELATIONS_KIND, keepMounted: true,
490
+ title: () => "会话",
491
+ }));
492
+ ui.slots.inject("sidebar.right.pane.tab", () => ui.slots.register({
493
+ name: "sidebar.right.pane.tab", key: RELATIONS_TAB, inject: () => ({ openSession, visibility, communication }),
494
+ }, RelationsTab));
495
+ ui.effect(() => {
496
+ capabilities = { sidebar, reveal, wasShown };
497
+ listeners.forEach(listener => listener());
498
+ return () => { capabilities = {}; listeners.forEach(listener => listener()); };
499
+ });
500
+ });
501
+ return scope.slots.inject("tool.call.toolview", () => scope.slots.register(
120
502
  {
121
503
  name: "tool.call.toolview",
122
504
  key: "session_create",
@@ -124,6 +506,7 @@ window.__ModuleLoader__.load({
124
506
  },
125
507
  SessionCreateRow,
126
508
  ));
509
+ };
127
510
  // Pre-0.2 hosts put UI selection on sessions. In 0.2 the Session
128
511
  // Controller only owns data/references; UIWorkspace owns mainView
129
512
  // retention, selection, panel reveal and release. Do not retain a
@@ -0,0 +1,101 @@
1
+ import { HarnessError } from '@deepseek-ai/dsh-llm';
2
+ import { symbols } from '@deepseek-ai/cordis';
3
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
4
+ import { z } from 'zod';
5
+
6
+ const recordSchema = z.object({
7
+ send: z.boolean(), receive: z.boolean(), revision: z.number().int().nonnegative().safe(),
8
+ }).strict();
9
+ const spec = defineDomain({
10
+ name: 'session_tools_communication', version: 1,
11
+ // Authoritative data: malformed records reject the whole domain, never skip.
12
+ tables: { sessions: domainTable(recordSchema) },
13
+ });
14
+ const states = new WeakMap();
15
+ const defaults = Object.freeze({ send: true, receive: true, revision: 0 });
16
+ export class CommunicationDenied extends HarnessError {
17
+ constructor(direction) {
18
+ super(`未送达、未排队:${direction === 'send' ? '来源会话已关闭发送。' : '目标会话已关闭接收。'}没有消息回执;通信权限改变前不要重复发送。`, 'session-tools/permission-denied');
19
+ this.name = 'CommunicationDenied';
20
+ }
21
+ }
22
+ export const sessionIdentitySchema = z.string().min(1).max(1024);
23
+ function sessionKey(id) {
24
+ sessionIdentitySchema.parse(id);
25
+ return id;
26
+ }
27
+ export function trustedSource(exec) { return sessionKey(exec?.agent?.session?.header?.id); }
28
+
29
+ /** One queue shared by all plugin instances, writes and final admissions alike. */
30
+ export function communicationPermissions(ctx) {
31
+ const service = ctx.get('storageDomain');
32
+ if (typeof service?.open !== 'function') throw new Error('Session communication controls require DSH 0.2.0-rc.2 storageDomain.');
33
+ const identity = service[symbols.original] ?? service;
34
+ let state = states.get(identity);
35
+ if (state) return state;
36
+ const ready = service.open(spec);
37
+ // Keep a malformed/unavailable domain closed, while avoiding unhandled rejection.
38
+ ready.catch(() => {});
39
+ let tail = Promise.resolve();
40
+ const serial = (action) => {
41
+ const result = tail.then(async () => action((await ready).table('sessions')));
42
+ tail = result.then(() => {}, () => {});
43
+ return result;
44
+ };
45
+ const read = (table, id) => ({ ...recordSchema.parse(table.get(sessionKey(id)) ?? defaults) });
46
+ const check = (table, sourceId, targetId) => {
47
+ if (!read(table, sourceId).send) throw new CommunicationDenied('send');
48
+ if (targetId !== undefined && !read(table, targetId).receive) throw new CommunicationDenied('receive');
49
+ };
50
+ state = {
51
+ get: (id) => serial(table => read(table, id)),
52
+ check: (sourceId, targetId) => serial(table => check(table, sourceId, targetId)),
53
+ // One authoritative snapshot for the current visible page; never retain it
54
+ // in discovery cursors. This is switch capability, not delivery or approval.
55
+ statuses: (sourceId, targetIds) => serial(table => {
56
+ const source = read(table, sourceId);
57
+ const checkedAt = Date.now();
58
+ return targetIds.map(targetId => {
59
+ const target = read(table, targetId);
60
+ const reason = !source.send && !target.receive ? 'both_disabled'
61
+ : !source.send ? 'sender_send_disabled' : !target.receive ? 'target_receive_disabled' : 'switches_allow';
62
+ return { state: source.send && target.receive ? 'allowed' : 'blocked', reason,
63
+ senderSend: source.send, targetReceive: target.receive, checkedAt };
64
+ });
65
+ }),
66
+ set: (id, patch, expectedRevision) => serial(async table => {
67
+ const parsed = recordSchema.parse({ ...patch, revision: expectedRevision });
68
+ const current = read(table, id);
69
+ if (current.revision !== expectedRevision) return { status: 'conflict', current };
70
+ if (current.revision === Number.MAX_SAFE_INTEGER) throw new Error('Permission revision exhausted');
71
+ const next = { send: parsed.send, receive: parsed.receive, revision: current.revision + 1 };
72
+ await table.put(sessionKey(id), next);
73
+ return { status: 'saved', current: { ...next } };
74
+ }),
75
+ // No await between the final synchronous read/check and followup callback.
76
+ admit: (sourceId, targetId, exec, followup) => serial(table => {
77
+ exec.signal?.throwIfAborted();
78
+ check(table, sourceId, targetId);
79
+ return followup();
80
+ }),
81
+ };
82
+ states.set(identity, state);
83
+ return state;
84
+ }
85
+
86
+ // Explicit unknown never invents open defaults when identity/storage is unavailable.
87
+ export const unknownCommunication = () => ({ state: 'unknown', reason: 'unavailable', checkedAt: Date.now() });
88
+ export const communicationStatusSchema = {
89
+ type: 'object', additionalProperties: false,
90
+ properties: {
91
+ state: { type: 'string', required: true, enum: ['allowed', 'blocked', 'unknown'] },
92
+ reason: { type: 'string', required: true, enum: ['switches_allow', 'sender_send_disabled', 'target_receive_disabled', 'both_disabled', 'unavailable'] },
93
+ senderSend: { type: 'boolean' }, targetReceive: { type: 'boolean' },
94
+ checkedAt: { type: 'number', required: true },
95
+ },
96
+ };
97
+ export function communicationStatusText(status) {
98
+ return ({ switches_allow: '通信开关允许', sender_send_disabled: '当前会话已关闭发送',
99
+ target_receive_disabled: '目标已关闭接收', both_disabled: '当前会话已关闭发送,目标已关闭接收',
100
+ unavailable: '通信状态无法确认' })[status.reason] ?? '通信状态无法确认';
101
+ }
@@ -0,0 +1,64 @@
1
+ import { symbols } from '@deepseek-ai/cordis';
2
+ import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
3
+ import { z } from 'zod';
4
+ import { communicationPermissions, sessionIdentitySchema } from './communication-permissions.js';
5
+
6
+ const sessionId = sessionIdentitySchema;
7
+ const getSchema = z.object({ sessionId }).strict();
8
+ const setSchema = z.object({ sessionId, send: z.boolean(), receive: z.boolean(), expectedRevision: z.number().int().nonnegative().safe() }).strict();
9
+ const recordSchema = z.object({ send: z.boolean(), receive: z.boolean(), revision: z.number().int().nonnegative().safe() }).strict();
10
+ const setResultSchema = z.object({ status: z.enum(['saved', 'conflict']), current: recordSchema }).strict();
11
+ export const communicationRemote = {
12
+ package: '@ryuu-64/dsh-session-tools',
13
+ descriptors: ['get', 'set'].map(method => ({
14
+ id: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}`,
15
+ service: 'sessionCommunication', namespace: 'sessionCommunication', method,
16
+ invocation: { kind: 'direct' },
17
+ parameters: [{ name: 'request', wire: 'request', source: 'json', codec: {
18
+ mode: 'strict', typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:request`,
19
+ create: () => method === 'get' ? getSchema : setSchema,
20
+ } }],
21
+ result: {
22
+ mode: 'strict', typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:result`,
23
+ create: () => method === 'get' ? recordSchema : setResultSchema,
24
+ },
25
+ })),
26
+ };
27
+ const initializers = [];
28
+ const original = value => value?.[symbols.original] ?? value;
29
+ /** A Remote UI surface only. No corresponding model tool is registered. */
30
+ export class CommunicationRemote extends TypertRemoteService {
31
+ static inject = ['typert', 'connection', 'storageDomain'];
32
+ constructor(ctx) {
33
+ super(ctx, 'sessionCommunication');
34
+ for (const initialize of initializers) initialize.call(this);
35
+ ctx.typert.register({
36
+ package: communicationRemote.package, face: 'host', schemas: [],
37
+ model: { services: [], events: [], objects: [] },
38
+ invocations: communicationRemote.descriptors,
39
+ });
40
+ }
41
+ authorize() {
42
+ const invocation = this.ctx.invocation;
43
+ const operator = this.ctx.connection.operator;
44
+ if (!invocation || !operator || original(invocation.peer) !== original(operator)) {
45
+ throw new RemoteError('gateway/bad-request', 'Only the authenticated host operator can read or change communication permissions.', {});
46
+ }
47
+ invocation.signal.throwIfAborted();
48
+ }
49
+ async get(request) {
50
+ this.authorize();
51
+ const parsed = getSchema.parse(request);
52
+ return await communicationPermissions(this.ctx).get(parsed.sessionId);
53
+ }
54
+ async set(request) {
55
+ this.authorize();
56
+ const parsed = setSchema.parse(request);
57
+ return await communicationPermissions(this.ctx).set(parsed.sessionId, { send: parsed.send, receive: parsed.receive }, parsed.expectedRevision);
58
+ }
59
+ }
60
+ // Apply the official standard-decorator initialization contract in plain JS.
61
+ for (const method of ['get', 'set']) Remote(CommunicationRemote.prototype[method], {
62
+ kind: 'method', name: method, static: false, private: false,
63
+ addInitializer: initialize => initializers.push(initialize),
64
+ });
package/lib/index.js CHANGED
@@ -10,6 +10,8 @@ import { fallbackSessionTitle } from "@deepseek-ai/dsh-session-title";
10
10
  import { receiptProjection, receiptProjectionKey, foldReceipts, messageReceipt } from "./message-receipts.js";
11
11
  import { createActivitySorter, readSlots } from "./session-activity.js";
12
12
  import { createSessionDiscovery } from "./session-discovery.js";
13
+ import { communicationPermissions, trustedSource, unknownCommunication, communicationStatusSchema, communicationStatusText } from "./communication-permissions.js";
14
+ import { CommunicationRemote } from "./communication-remote.js";
13
15
 
14
16
  /** Stable Loader identity and producer-owned message source (V3 and V4). */
15
17
  const name = "tool-session";
@@ -25,7 +27,8 @@ const inject = [
25
27
  "agents",
26
28
  "sessionTitle",
27
29
  "workspaceRegistry",
28
- "agentDefaultModel"
30
+ "agentDefaultModel",
31
+ "storageDomain"
29
32
  ];
30
33
  /** List the existing workspaces, so a rejected path tells the caller what to use instead. */
31
34
  function workspaceCatalogue(registry) {
@@ -242,11 +245,18 @@ const receiptProperties = {
242
245
  output: { type: "string" }
243
246
  };
244
247
 
248
+ function receiptMeta(value) {
249
+ return Object.fromEntries(["sessionId", "messageId", "messageStatus", "waitStatus", "turn", "turnEndKind", "attributionNote"].filter(key => value[key] !== undefined).map(key => [key, value[key]]));
250
+ }
251
+ const statusLabels = {
252
+ queued: "已排队", delivered: "已交给目标", turnCompleted: "目标本轮结束(不等于任务成功)",
253
+ discarded: "取消", cancelled: "取消", interrupted: "中断", failed: "失败",
254
+ incomplete: "未完整结束", blocked: "未完整结束", unknown: "暂无法确认",
255
+ };
245
256
  function receiptText(value) {
246
257
  const receipt = `Receipt: sessionId=${value.sessionId}, messageId=${value.messageId}`;
247
258
  const notice = waitNotice(value);
248
- return `${receipt}\nMessage status: ${value.messageStatus ?? "queued"}${value.turn === undefined ? "" : `; turn ${value.turn}`}.` +
249
- (value.messageStatus === "turnCompleted" ? " The recorded turn completed; this does not verify the business task succeeded." : "") +
259
+ return `${statusLabels[value.messageStatus] ?? "暂无法确认"}\n${receipt}` +
250
260
  (value.attributionNote ? `\n${value.attributionNote}` : "") + (notice ? `\n${notice}` : "") +
251
261
  (value.output === undefined ? "" : `\n${value.output}`);
252
262
  }
@@ -410,9 +420,45 @@ async function resolveTargetAgent(ctx, sessionId, exec) {
410
420
  * @param ctx - services of the agent this plugin was loaded for.
411
421
  */
412
422
  function apply(ctx) {
423
+ const permissions = communicationPermissions(ctx);
424
+ ctx.inject(["typert", "connection"], scope => { scope.plugin(CommunicationRemote); });
413
425
  const inSlot = readSlots();
414
426
  const sortByActivity = createActivitySorter(ctx, inSlot);
415
427
  const listSessions = createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState);
428
+ ctx.tools.register(defineTool({
429
+ name: "session_communication_status",
430
+ description: "Read whether this session's send switch and a visible ordinary target's receive switch currently allow communication. Optional: use when you only want to check a known target, including whether it has reopened. This does not send, wake, subscribe, grant approval, or guarantee later delivery. Normal sends need no separate preflight; session_send always rechecks.",
431
+ parameters: { sessionId: { type: "string", required: true, description: "Target ordinary session ID." } },
432
+ output: {
433
+ schema: { type: "object", additionalProperties: false, properties: {
434
+ sessionId: { type: "string", required: true },
435
+ communication: { ...communicationStatusSchema, required: true },
436
+ } },
437
+ render: (_args, value) => [{ type: "text", text: `${communicationStatusText(value.communication)}。仅为当前开关状态,不代表已投递,也不替代审批和其他发送限制;发送时仍会重检。` }],
438
+ },
439
+ async execute(args, exec) {
440
+ const requested = args.sessionId.trim();
441
+ let communication = unknownCommunication();
442
+ try {
443
+ const sourceId = trustedSource(exec);
444
+ if (!requested || requested.length > 1024) return { sessionId: requested, communication };
445
+ // Resolve visibility before reading permissions: arbitrary IDs must
446
+ // never reveal defaults or records outside the host's catalog.
447
+ const query = ctx.get("sessionQuery");
448
+ if (!query) return { sessionId: requested, communication };
449
+ const record = (await query.listSessions(exec.signal)).find(row =>
450
+ String(row.header.id) === requested && (row.header.delegationDepth ?? 0) <= 0 && row.header.origin !== "subagent");
451
+ exec.signal?.throwIfAborted();
452
+ if (!record) return { sessionId: requested, communication };
453
+ // Read switch state only. cwd/self and other delivery restrictions
454
+ // remain session_send concerns, just as for list_sessions rows.
455
+ [communication] = await permissions.statuses(sourceId, [requested]);
456
+ } catch {
457
+ exec.signal?.throwIfAborted();
458
+ }
459
+ return { sessionId: requested, communication };
460
+ },
461
+ }));
416
462
  // Optional capability; the same pure fold also works over a read-only full log.
417
463
  if (typeof ctx.inject === "function") ctx.inject(["sessionProjections"], scope => {
418
464
  scope.sessionProjections.register(receiptProjection);
@@ -474,6 +520,7 @@ function apply(ctx) {
474
520
  // ToolResultNode.meta. The canonical value alone does not survive replay.
475
521
  presentationMeta: (_args, value) => ({
476
522
  sessionId: value.sessionId,
523
+ ...receiptMeta(value),
477
524
  ...typeof value.title === "string" ? { title: value.title } : {}
478
525
  }),
479
526
  // Keep the receipt readable for clients without the session card.
@@ -486,6 +533,8 @@ function apply(ctx) {
486
533
  },
487
534
  async execute(args, exec) {
488
535
  if (exec.agent === void 0) throw new Error("session_create must run inside a session");
536
+ const sourceId = trustedSource(exec);
537
+ await permissions.check(sourceId);
489
538
  const prompt = args.prompt.trim();
490
539
  if (prompt === "") throw new Error("session_create needs a prompt: it becomes the new session's first user message");
491
540
  let workspace;
@@ -505,7 +554,9 @@ function apply(ctx) {
505
554
  // Ask before creating anything: a session that appears in the person's
506
555
  // list without them knowing about it is the whole risk of this tool.
507
556
  const where = workspace === void 0 ? "ungrouped" : `in workspace ${JSON.stringify(workspace.path)}`;
557
+ await permissions.check(sourceId);
508
558
  await requireApproval(ctx, exec, `create a new session ${where}, starting with: ${prompt.slice(0, 120)}`);
559
+ await permissions.check(sourceId);
509
560
  const agentOptions = currentSelection(ctx, exec.agent);
510
561
  const agentPresets = ctx.get("agentPresets");
511
562
  const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
@@ -549,7 +600,7 @@ function apply(ctx) {
549
600
  form: "relay"
550
601
  }
551
602
  });
552
- handle.agent.followup(sent);
603
+ await permissions.admit(sourceId, String(sessionId), exec, () => handle.agent.followup(sent));
553
604
  } catch (error) {
554
605
  if (attached) try {
555
606
  await workspace.detachSession(sessionId);
@@ -625,7 +676,7 @@ function apply(ctx) {
625
676
  ...receiptProperties
626
677
  }
627
678
  },
628
- presentationMeta: (_args, value) => ({ sessionId: value.sessionId, messageId: value.messageId }),
679
+ presentationMeta: (_args, value) => receiptMeta(value),
629
680
  render: (_args, value) => [{
630
681
  type: "text",
631
682
  text: receiptText(value)
@@ -633,12 +684,16 @@ function apply(ctx) {
633
684
  },
634
685
  async execute(args, exec) {
635
686
  if (exec.agent === void 0) throw new Error("session_send must run inside a session");
687
+ const sourceId = trustedSource(exec);
636
688
  const requested = args.sessionId.trim();
637
689
  if (requested === "") throw new Error("session_send needs a session id");
638
690
  const message = args.message.trim();
639
691
  if (message === "") throw new Error("session_send needs a message");
692
+ await permissions.check(sourceId, requested);
640
693
  await inspectSendTarget(ctx, requested, exec);
694
+ await permissions.check(sourceId, requested);
641
695
  await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(requested)}: ${message.slice(0, 120)}`);
696
+ await permissions.check(sourceId, requested);
642
697
  const target = await resolveTargetAgent(ctx, requested, exec);
643
698
  exec.signal?.throwIfAborted();
644
699
  const targetId = String(target.id);
@@ -654,7 +709,7 @@ function apply(ctx) {
654
709
  form: "relay"
655
710
  }
656
711
  });
657
- target.followup(sent);
712
+ await permissions.admit(sourceId, targetId, exec, () => target.followup(sent));
658
713
  if (args.wait !== true) return {
659
714
  sessionId: targetId,
660
715
  messageId: sent.id,
@@ -673,7 +728,7 @@ function apply(ctx) {
673
728
  }));
674
729
  ctx.tools.register(defineTool({
675
730
  name: "list_sessions",
676
- description: "List the sessions the person can see, most recent conversation activity first, with each id and current state (working, waiting, or put away). New input, model output/attempts, execution starts and non-recovery turn endings count. Bare step/tool completion, title-only changes and recovery do not advance activity. Sessions without conversation activity use creation time; ties keep the host's order. Use it before session_send when the target is described by name rather than by id.",
731
+ description: "List the sessions the person can see, most recent conversation activity first, with each id and current state (working, waiting, or put away). New input, model output/attempts, execution starts and non-recovery turn endings count. Bare step/tool completion, title-only changes and recovery do not advance activity. Sessions without conversation activity use creation time; ties keep the host's order. Use it before session_send when the target is described by name rather than by id. Each row includes a fresh caller-to-target communication-switch snapshot, not approval or a delivery guarantee; never cache it as permission to send.",
677
732
  parameters: {
678
733
  titleQuery: { type: "string", description: "Literal title substring, NFC/whitespace normalized and case-insensitive; at most 1024 UTF-8 bytes. Applied before limit. A failed title read fails the complete query." },
679
734
  workspaceId: { type: "string", description: "Existing workspace ID (at most 256 UTF-8 bytes); mutually exclusive with workspacePath. Uses actual workspace membership." },
@@ -709,7 +764,8 @@ function apply(ctx) {
709
764
  description: "What the session is doing right now: running (working on a turn), idle (open or saved, not working), archived (put away from the sidebar)."
710
765
  },
711
766
  current: { type: "boolean" },
712
- subagent: { type: "boolean" }
767
+ subagent: { type: "boolean" },
768
+ communication: { ...communicationStatusSchema, required: true }
713
769
  }
714
770
  }
715
771
  },
@@ -737,8 +793,10 @@ function apply(ctx) {
737
793
  entry.subagent === true ? "(subagent)" : undefined,
738
794
  entry.state === "running" ? "(working now)" : undefined,
739
795
  entry.state === "archived" ? "(put away)" : undefined,
740
- entry.cwd
796
+ entry.cwd,
797
+ communicationStatusText(entry.communication)
741
798
  ].filter((part) => part !== undefined).join(" · ")).join("\n"),
799
+ "通信状态仅为当前开关快照,不替代审批或其他发送限制;发送时仍重检。",
742
800
  value.sessions.some((entry) => entry.state === "archived") ? "Sessions marked (put away) are archived: they are hidden from the sidebar but still listed here." : undefined,
743
801
  value.nextCursor ? `More matching sessions: use nextCursor ${value.nextCursor} before ${new Date(value.resultSetExpiresAt).toISOString()}.` : undefined,
744
802
  value.paginationUnavailable
@@ -788,6 +846,7 @@ function apply(ctx) {
788
846
  ...receiptProperties
789
847
  }
790
848
  },
849
+ presentationMeta: (_args, value) => ({ ...receiptMeta(value), scope: value.scope }),
791
850
  render: (_args, value) => [{
792
851
  type: "text",
793
852
  text: value.scope === "message" ? receiptText(value) :
@@ -1,6 +1,7 @@
1
1
  import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { isAbsolute } from "node:path";
3
3
  import { symbols } from "@deepseek-ai/cordis";
4
+ import { communicationPermissions, trustedSource, unknownCommunication } from "./communication-permissions.js";
4
5
 
5
6
  // Resource guards, not measured throughput promises. No event/log/Agent is retained.
6
7
  const TTL = 5 * 60_000;
@@ -160,8 +161,16 @@ export function createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState
160
161
  set.bytes = Buffer.byteLength(JSON.stringify(set));
161
162
  if (owner && rows.length > limit && set.bytes > MAX_BYTES) throw fail("result set exceeds the 8 MiB metadata budget; narrow the query");
162
163
  }
164
+ const page = set.rows.slice(offset, offset + limit);
165
+ let communication;
166
+ try {
167
+ communication = await communicationPermissions(ctx).statuses(trustedSource(exec), page.map(row => row.id));
168
+ } catch {
169
+ communication = page.map(() => unknownCommunication());
170
+ }
171
+ exec.signal?.throwIfAborted();
163
172
  const listed = [];
164
- for (const row of set.rows.slice(offset, offset + limit)) {
173
+ for (const [pageIndex, row] of page.entries()) {
165
174
  exec.signal?.throwIfAborted();
166
175
  const header = byId.get(row.id).header;
167
176
  let title = row.title;
@@ -170,7 +179,7 @@ export function createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState
170
179
  title = (await inSlot(() => query.readTitle(row.id, exec.signal), exec.signal))?.title;
171
180
  } catch {}
172
181
  exec.signal?.throwIfAborted();
173
- listed.push({ sessionId: row.id,
182
+ listed.push({ sessionId: row.id, communication: communication[pageIndex],
174
183
  ...title === undefined || title === "" ? {} : { title: String(title) },
175
184
  ...header.cwd === undefined ? {} : { cwd: String(header.cwd) },
176
185
  state: sessionState(ctx, row.id), ...row.id === owner ? { current: true } : {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ryuu-64/dsh-session-tools",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Let the agent start a new chat session, send a message to another one, or wait for it to finish.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,7 +34,9 @@
34
34
  "inject": [
35
35
  "@deepseek-ai/dsh-client-ui-slots",
36
36
  "@deepseek-ai/dsh-client-ui-tool",
37
- "@deepseek-ai/dsh-client-ui-workspace"
37
+ "@deepseek-ai/dsh-client-ui-workspace",
38
+ "@deepseek-ai/dsh-api-gateway",
39
+ "@deepseek-ai/dsh-client-ui-sidebar-right"
38
40
  ]
39
41
  }
40
42
  },
@@ -44,15 +46,19 @@
44
46
  },
45
47
  "peerDependencies": {
46
48
  "@deepseek-ai/cordis": "^4.0.2",
47
- "@deepseek-ai/dsh-agent": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
48
- "@deepseek-ai/dsh-agent-default-model": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
49
- "@deepseek-ai/dsh-brand": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
50
- "@deepseek-ai/dsh-llm": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
51
- "@deepseek-ai/dsh-session-title": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
52
- "@deepseek-ai/dsh-tools": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
53
- "@deepseek-ai/dsh-workspace": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
49
+ "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
50
+ "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
51
+ "@deepseek-ai/dsh-brand": "0.2.0-rc.2",
52
+ "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
53
+ "@deepseek-ai/dsh-session-title": "0.2.0-rc.2",
54
+ "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
55
+ "@deepseek-ai/dsh-workspace": "0.2.0-rc.2",
54
56
  "@deepseek-ai/schemastery": "^3.18.2",
55
- "react": ">=18 <20"
57
+ "react": ">=18 <20",
58
+ "@deepseek-ai/dsh-storage-domain": "0.2.0-rc.2",
59
+ "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
60
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.0-rc.2",
61
+ "@deepseek-ai/dsh-client-ui-sidebar-right": "0.1.7-alpha.1 || 0.1.7-alpha.2 || 0.1.7-rc.1 || 0.1.7-rc.2 || 0.2.0-rc.1 || 0.2.0-rc.2"
56
62
  },
57
63
  "files": [
58
64
  "lib",
@@ -64,6 +70,8 @@
64
70
  },
65
71
  "devDependencies": {
66
72
  "@deepseek-ai/cordis": "4.0.4",
73
+ "@deepseek-ai/cordis-plugin-group": "1.0.4",
74
+ "@deepseek-ai/cordis-plugin-include": "1.0.9",
67
75
  "@deepseek-ai/cordis-plugin-loader": "1.0.5",
68
76
  "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
69
77
  "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
@@ -100,6 +108,9 @@
100
108
  "zustand": "4.4.7"
101
109
  },
102
110
  "overrides": {
111
+ "@deepseek-ai/cordis-plugin-group": "1.0.4",
112
+ "@deepseek-ai/cordis-plugin-include": "1.0.9",
113
+ "@deepseek-ai/cordis-plugin-loader": "1.0.5",
103
114
  "@deepseek-ai/dsh-scope": "0.2.0-rc.2",
104
115
  "@deepseek-ai/dsh-invariants": "0.2.0-rc.2",
105
116
  "@deepseek-ai/dsh-util-values": "0.2.0-rc.2",