@ryuu-64/dsh-session-tools 0.4.2 → 0.5.3

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
@@ -1,10 +1,10 @@
1
1
  # dsh-session-tools
2
2
 
3
- 让对话里的 AI 能做两件事:**新建一个会话**,或者**给别的会话发一条消息**。
3
+ 让对话里的 AI 能**新建会话**、**给别的会话发消息**、**看看有哪些会话**,以及**等别的会话干完活**。
4
4
 
5
- 两个工具,`session_create` 和 `session_send`。新会话会出现在左侧会话列表里,和手动新建的完全一样;想让它归到某个工作区下面也可以。
5
+ 四个工具,`session_create`、`session_send`、`list_sessions`、`session_wait`。新会话会出现在左侧会话列表里,和手动新建的完全一样;想让它归到某个工作区下面也可以。
6
6
 
7
- 典型用法:你说"帮我开一个会话去查一下这件事"——AI 直接建好,不用你自己新建再复制粘贴。
7
+ 典型用法:你说"帮我开一个会话去查一下这件事"——AI 直接建好,不用你自己新建再复制粘贴。或者你已经有一个会话在跑,说"等它弄完把结果告诉我",AI 把活派过去,等它做完了再回来接着讲。
8
8
 
9
9
  ## session_create:新建会话
10
10
 
@@ -15,7 +15,7 @@
15
15
  | `title` | 可选 | 会话标题。不填就和手动新建一样,由第一句话自动生成。 |
16
16
  | `wait` | 可选 | 默认不等。只有一种情况需要等:你要在新建的那个会话跑完第一轮之后才继续。 |
17
17
 
18
- 做完返回新会话的 id、所属工作区、工作目录。如果中途失败,会把建了一半的东西清理掉,不留垃圾。
18
+ 做完返回新会话的名字和 id,你在左侧列表里就能看到它。如果中途失败,会把建了一半的东西清理掉,不留垃圾。
19
19
 
20
20
  ## session_send:给别的会话发消息
21
21
 
@@ -23,13 +23,62 @@
23
23
  |---|---|---|
24
24
  | `sessionId` | 必填 | 目标会话的 id,形如 `session-9311a0fb-65c7-4b04-b142-1444642a627e`。 |
25
25
  | `message` | 必填 | 要发的内容。对方看不到当前这个会话,所以要写清楚。 |
26
+ | `wait` | 可选 | 默认不等:发出去就返回。填 `true` 就等对方把这条消息处理完,并把它的回答带回来。 |
27
+ | `timeoutMs` | 可选 | 等多久(毫秒)。默认 60000(一分钟),最多 300000(五分钟)。等超了不报错,只告诉你"它还在忙"。 |
26
28
 
27
- 发出即返回,返回只代表对方收到了、开始排队处理。消息来源标记为插件,不会被当成是你本人打的字。
29
+ 默认发出即返回,返回只代表对方收到了、开始排队处理。消息来源标记为插件,不会被当成是你本人打的字。目标会话如果没开着,会被自动打开再把消息排进去。
30
+
31
+ 填了 `wait` 就变成"发完等它做完",AI 拿到对方的回答之后可以接着往下办——比如让一个会话去跑测试,跑完再根据结果决定下一步。
32
+
33
+ ## session_wait:等别的会话干完
34
+
35
+ 如果消息已经发出去了,或者那个会话本来就在忙,用这个等它收尾。
36
+
37
+ | 参数 | 是否必填 | 说明 |
38
+ |---|---|---|
39
+ | `sessionId` | 必填 | 目标会话的 id。 |
40
+ | `timeoutMs` | 可选 | 等多久(毫秒),默认 60000,最多 300000。 |
41
+
42
+ 它只负责等和看,不去动那个会话:不会打开它、不会改它、也不会打断它。对方本来就没在忙的话,立刻返回,把最后一条回答给你。等超了就说一句"还在忙",不算失败——你可以过会儿再问一次。
43
+
44
+ ## list_sessions:先看看有哪些会话
45
+
46
+ 不用记 id。当你要说的是"发给那个讨论发布的会话",AI 可以先列出会话(名字、目录、哪个是当前会话、现在在干什么),你说清是哪一个,它再发。
47
+
48
+ | 参数 | 是否必填 | 说明 |
49
+ |---|---|---|
50
+ | `limit` | 可选 | 最多列几个,默认 20,按最近活动排序。 |
51
+
52
+ 每条会带一个状态,就是侧边栏上显示的那个东西:
53
+
54
+ | 状态 | 意思 |
55
+ |---|---|
56
+ | `running` | 进行中,正忙着。 |
57
+ | `idle` | 空闲,没在干活(开着或者躺着都算)。 |
58
+ | `archived` | 已归档,你把它从侧边栏收起来了。 |
59
+
60
+ 子代理会话不会列出来(那是 AI 自己派出去的活)。
61
+
62
+ ## 动手前会先问你
63
+
64
+ 新建会话、或者往别的会话发消息,**都会先弹一个确认卡**,写清它要干什么,比如:
65
+
66
+ > 允许一次:在工作区 `E:\Users\Ryuu\Desktop` 新建会话,内容是「查一下某件事」
67
+
68
+ 你点了"允许一次"它才动手;拒绝或没应答,它就什么都不做。你自己完全关掉审批(切到完全权限模式)时,它不再打扰你——那是你的选择,不是它擅自跳过。
69
+
70
+ 只是等一个会话做完、或者列一下有哪些会话,不会弹卡:这两件事不往任何地方写东西。
71
+
72
+ ## 建好的会话,卡片上点一下就能过去
73
+
74
+ 做完之后,对话里那张卡片会变成「已创建会话」加一个按钮——**点一下直接跳到新建的那个会话**,不用去左侧列表里找。
75
+
76
+ (这一部分由插件的浏览器端负责渲染,所以旧的对话记录也会跟着变成可点。)
28
77
 
29
78
  ## 安装
30
79
 
31
80
  ```
32
- dsh plugin --profile desktop add @ryuu-64/dsh-session-tools@0.4.2
81
+ dsh plugin --profile desktop add @ryuu-64/dsh-session-tools@0.5.3
33
82
  ```
34
83
 
35
84
  从源码装:
@@ -45,6 +94,6 @@ dsh plugin --profile desktop add link:C:\path\to\dsh-session-tools
45
94
 
46
95
  - **不会顺手新建工作区**。`workspacePath` 必须是已经存在的那个工作区的路径;写错了它会报错,并把现有的工作区列出来给你挑。
47
96
  - **不能给子代理发消息**。目标必须是普通会话;AI 派出去的子代理要用 `send_message`。也不能给当前这个会话自己发。
48
- - **重启期间收不到**。新建会话是立刻生效的;发出去的消息要等对方会话被打开处理,所以 DSH 得开着。
97
+ - **重启期间收不到**。新建会话是立刻生效的;发出去的消息要等对方会话被打开处理,所以 DSH 得开着。等待也一样,DSH 关了就没法等。
49
98
  - **归属定了就不能改**。会话归到哪个工作区是记在账上的,建完之后没法在工作区之间搬。
50
- - **桌面版可用**。命令行无界面模式(headless)默认不带工作区功能,要用得自己加一行配置。
99
+ - **需要桌面版**。工作区归属靠桌面版才挂载的那个工作区服务,插件把它列为必需依赖,所以命令行无界面模式(headless)下这个插件不会加载。
package/lib/client.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Browser half: render the `session_create` tool card as something the person
3
+ * can act on. The host half prints a receipt; this half turns the session that
4
+ * receipt names into a button that opens it.
5
+ *
6
+ * Loaded by the browser module table as a CJS closure factory; `require` resolves
7
+ * only platform seeds and other registered bundles.
8
+ */
9
+ window.__ModuleLoader__.load({
10
+ id: "@ryuu-64/dsh-session-tools",
11
+ factory: (require) => {
12
+ var module = { exports: {} };
13
+ var exports = module.exports;
14
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
15
+
16
+ const react = require("react");
17
+
18
+ /** Slots this client half needs before it can register anything. */
19
+ const inject = ["slots", "sessions"];
20
+
21
+ /** Diagnostics stay behind one switch so a quiet console stays quiet. */
22
+ const DEBUG = false;
23
+
24
+ /**
25
+ * Flatten a settled result's content blocks, mirroring how `ui-tool` reads
26
+ * them: text blocks verbatim, anything else as JSON.
27
+ * @param node - a candidate settled result node.
28
+ * @returns the flattened text, or "" when this is not a result node.
29
+ */
30
+ function resultText(node) {
31
+ if (node === null || typeof node !== "object" || !Array.isArray(node.content)) return "";
32
+ return node.content
33
+ .map((part) => (part !== null && typeof part === "object" && part.type === "text" && typeof part.text === "string"
34
+ ? part.text
35
+ : JSON.stringify(part)))
36
+ .join("\n");
37
+ }
38
+
39
+ /**
40
+ * Read the created session out of a settled tool result.
41
+ *
42
+ * The result node's `content` blocks are the form the host half guarantees,
43
+ * so they are the first source; a structured value is used when present.
44
+ * Both are read defensively: this half must never break the transcript when
45
+ * a shape changes underneath it.
46
+ * @param block - the settled tool call block handed to the slot.
47
+ * @param output - the owner's rendered result text, when it passes one.
48
+ * @returns the session id and optional title, or undefined.
49
+ */
50
+ function readCreatedSession(block, output) {
51
+ if (block === null || typeof block !== "object") return undefined;
52
+ // Settled results expose `content` directly; a raw event nests them under `result`.
53
+ const settled = Array.isArray(block.content) ? block : block.result ?? block;
54
+ if (DEBUG) {
55
+ try {
56
+ console.log("[session-tools] block:", Object.keys(block), "settled:", Object.keys(settled), "output:", String(output ?? "").slice(0, 160));
57
+ } catch {}
58
+ }
59
+ for (const candidate of [settled.value, settled.output, block.value, block.output]) {
60
+ if (candidate !== null && typeof candidate === "object" && typeof candidate.sessionId === "string") {
61
+ return { sessionId: candidate.sessionId, title: typeof candidate.title === "string" ? candidate.title : undefined };
62
+ }
63
+ }
64
+ const text = [resultText(settled), typeof output === "string" ? output : ""].filter((part) => part !== "").join("\n");
65
+ const id = /session-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/u.exec(text)?.[0];
66
+ if (id === undefined) return undefined;
67
+ const title = /Created session:\s*(.+?)\s+·\s+session-/u.exec(text)?.[1];
68
+ return { sessionId: id, title };
69
+ }
70
+
71
+ /**
72
+ * One row for a finished `session_create` call: what was created, and a
73
+ * button that opens it in the conversation area.
74
+ * @param props - slot owner props plus the injected `openSession`.
75
+ * @returns the row element.
76
+ */
77
+ function SessionCreateRow(props) {
78
+ const openSession = props.openSession ?? props.slot?.injected?.openSession;
79
+ // The owner hands over the raw result node; `output` is its rendered text.
80
+ // Reading both makes the row survive a shape change on either side.
81
+ const created = readCreatedSession(props.block, props.output);
82
+ const title = created?.title === undefined || created.title === "" ? "会话" : created.title;
83
+ const canOpen = created !== undefined && typeof openSession === "function";
84
+ const onOpen = () => {
85
+ if (!canOpen) return;
86
+ try {
87
+ openSession(created.sessionId);
88
+ } catch (error) {
89
+ console.error("[session-tools] opening the session failed:", error);
90
+ }
91
+ };
92
+ return react.createElement(
93
+ "div",
94
+ {
95
+ style: {
96
+ display: "flex",
97
+ alignItems: "center",
98
+ gap: "8px",
99
+ flexWrap: "wrap",
100
+ fontSize: "13px",
101
+ },
102
+ },
103
+ react.createElement("span", null, "已创建会话"),
104
+ react.createElement(
105
+ "button",
106
+ {
107
+ type: "button",
108
+ onClick: onOpen,
109
+ disabled: !canOpen,
110
+ title: created?.sessionId ?? "没有读到会话 id",
111
+ style: {
112
+ border: "1px solid var(--dsh-border, #3a4150)",
113
+ background: "transparent",
114
+ color: "inherit",
115
+ borderRadius: "999px",
116
+ padding: "1px 10px",
117
+ cursor: canOpen ? "pointer" : "default",
118
+ font: "inherit",
119
+ opacity: canOpen ? "1" : "0.55",
120
+ },
121
+ },
122
+ title,
123
+ ),
124
+ created === undefined ? react.createElement("span", { style: { opacity: 0.6 } }, "(结果里没有会话信息)") : null,
125
+ created === undefined ? null : react.createElement("span", { style: { opacity: 0.55, fontFamily: "ui-monospace, monospace", fontSize: "11px" } }, created.sessionId),
126
+ );
127
+ }
128
+
129
+ /**
130
+ * Wait for the tool view slot list to exist, then register a keyed row that
131
+ * replaces the default card for `session_create`.
132
+ * @param ctx - the browser plugin context.
133
+ */
134
+ function apply(ctx) {
135
+ ctx.slots.inject("tool.call.toolview", () => ctx.slots.register(
136
+ {
137
+ name: "tool.call.toolview",
138
+ key: "session_create",
139
+ inject: () => ({ openSession: (sessionId) => ctx.sessions.open(sessionId) }),
140
+ },
141
+ SessionCreateRow,
142
+ ));
143
+ }
144
+
145
+ exports.apply = apply;
146
+ exports.inject = inject;
147
+ return module.exports;
148
+ },
149
+ });
package/lib/index.js CHANGED
@@ -23,6 +23,58 @@ function workspaceCatalogue(registry) {
23
23
  return items.map((workspace) => `${workspace.title} (${workspace.path})`).join("; ");
24
24
  }
25
25
  /**
26
+ * Name a session in tool output, the way a person would say it: the title they
27
+ * will see in the sidebar, plus the id when the title is not known yet.
28
+ *
29
+ * Deliberately NOT the `@[label](dsh-session:…)` mention form. That form renders
30
+ * as a chip in message text but carries no navigation — it is a label, not a
31
+ * link — and whether it renders at all depends on machinery a tool result does
32
+ * not have. A receipt should read the same everywhere.
33
+ * @param title - the session's title, when it is known yet.
34
+ * @param sessionId - the session's id.
35
+ * @returns one line naming the session.
36
+ */
37
+ function sessionReference(title, sessionId) {
38
+ // Title reads hand back a snapshot, not a string; take the text either way so
39
+ // a receipt can never print an object.
40
+ const raw = typeof title === "object" && title !== null ? title.title : title;
41
+ const label = typeof raw === "string" ? raw.trim() : "";
42
+ return label === "" ? sessionId : `${label} · ${sessionId}`;
43
+ }
44
+ /**
45
+ * Ask the person before touching another session. The approval service applies
46
+ * the session's own policy, so this asks only when that policy is `ask`; a
47
+ * `never` policy means the person already turned prompts off, which is not the
48
+ * same as refusing, so the action proceeds.
49
+ * @param ctx - services of the calling agent.
50
+ * @param exec - the running tool execution, for the agent and call id.
51
+ * @param reason - what is about to happen, in the person's own terms.
52
+ * @returns nothing; throws when the action was refused.
53
+ * @throws when no approval channel is available (fail closed) or the person refused.
54
+ */
55
+ async function requireApproval(ctx, exec, reason) {
56
+ const approval = ctx.get("approval");
57
+ if (approval === void 0) {
58
+ // No approval capability in this composition: do not act on another session
59
+ // without a way to ask, because the person would never see it happen.
60
+ throw new Error(`this DSH cannot ask for approval, so ${reason} was not done`);
61
+ }
62
+ const policy = approval.effectivePolicy(exec.agent.session);
63
+ if (policy !== "ask") return;
64
+ const outcome = await approval.request({
65
+ agent: exec.agent,
66
+ toolName: exec.name,
67
+ callId: exec.callId,
68
+ reason
69
+ });
70
+ if (outcome === "allowed-once") return;
71
+ throw new Error(
72
+ outcome === "rejected"
73
+ ? `the person declined: ${reason} was not done`
74
+ : `no answer to the approval request, so ${reason} was not done (${outcome})`
75
+ );
76
+ }
77
+ /**
26
78
  * Give the new session the same model as this one: read the model the calling
27
79
  * session is using, and fall back to the default when it has not chosen one.
28
80
  */
@@ -67,6 +119,64 @@ async function resolvePreset(ctx, agent, presets) {
67
119
  }
68
120
  }
69
121
  /**
122
+ * Bound a wait request to a usable budget: a missing or nonsensical value falls
123
+ * back to the default, and the ceiling keeps one tool call from hanging a turn
124
+ * forever. A timeout is reported, never treated as an error.
125
+ * @param requested - the caller's requested budget in milliseconds, if any.
126
+ * @returns the budget actually used.
127
+ */
128
+ function waitBudgetMs(requested) {
129
+ const DEFAULT_MS = 60_000;
130
+ const MAX_MS = 300_000;
131
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return DEFAULT_MS;
132
+ return Math.min(Math.trunc(requested), MAX_MS);
133
+ }
134
+ /**
135
+ * Read a session's final answer, applying the same rule the host uses for a
136
+ * subagent's result: the LAST non-empty assistant message wins, and the
137
+ * accumulated assistant text is the fallback when no message qualifies
138
+ * (`@deepseek-ai/dsh-subagent`'s assistant-output rule). Text blocks are joined
139
+ * verbatim between them, matching that package's `finalText`.
140
+ * @param ctx - services of the calling agent.
141
+ * @param sessionId - the session to read.
142
+ * @param signal - optional cancellation for the persisted-log read.
143
+ * @returns the final text, or undefined when the session has no assistant reply.
144
+ */
145
+ async function readFinalAnswer(ctx, sessionId) {
146
+ const live = ctx.agents.get(sessionId);
147
+ const own = typeof live?.session?.snapshotEvents === "function" ? live.session.snapshotEvents() : undefined;
148
+ let events = own;
149
+ if (events === undefined) {
150
+ const query = ctx.get("sessionQuery");
151
+ if (query === void 0) throw new Error(`this DSH cannot read session ${JSON.stringify(sessionId)}`);
152
+ // Reads the log without making the session live, so waiting stays read-only.
153
+ events = (await query.readSession(sessionId)).events;
154
+ }
155
+ const texts = (content) => (content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("");
156
+ let answer;
157
+ const accumulated = [];
158
+ for (const event of events) {
159
+ if (event.type !== "assistant/message") continue;
160
+ const text = texts(event.data.message?.content);
161
+ if (text.trim() !== "") answer = text;
162
+ else accumulated.push(text);
163
+ }
164
+ const found = answer ?? (accumulated.length === 0 ? undefined : accumulated.join(""));
165
+ return found === undefined || found.trim() === "" ? undefined : found;
166
+ }
167
+ /**
168
+ * Report what a session is doing right now: working, waiting, or put away. The
169
+ * archive set lives on the workspace registry and answers whether the person has
170
+ * hidden the session from the sidebar, so it needs no log read of its own.
171
+ * @param ctx - services of the calling agent.
172
+ * @param sessionId - the session to describe.
173
+ * @returns `"running"`, `"archived"`, or `"idle"`.
174
+ */
175
+ function sessionState(ctx, sessionId) {
176
+ if (ctx.get("workspaceRegistry")?.archivedSessionIds?.some((id) => String(id) === sessionId) === true) return "archived";
177
+ return ctx.agents.get(sessionId)?.status === "running" ? "running" : "idle";
178
+ }
179
+ /**
70
180
  * Get the live agent for a target session, opening the session again when it is
71
181
  * not currently running. The session is reopened on the preset it was created
72
182
  * with.
@@ -145,12 +255,17 @@ function apply(ctx) {
145
255
  required: true
146
256
  },
147
257
  workspaceId: { type: "string" },
148
- workspacePath: { type: "string" }
258
+ workspacePath: { type: "string" },
259
+ title: { type: "string" }
149
260
  }
150
261
  },
262
+ // The card is the receipt: it names the session, so the person can find it
263
+ // in the sidebar without digging a session id out of a log.
151
264
  render: (_args, value) => [{
152
265
  type: "text",
153
- text: value.grouped ? `Created session ${value.sessionId} in workspace ${value.workspacePath}` : `Created session ${value.sessionId}, ungrouped`
266
+ text: value.grouped === true
267
+ ? `Created session: ${sessionReference(value.title, value.sessionId)} in workspace ${value.workspacePath}`
268
+ : `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`
154
269
  }]
155
270
  },
156
271
  async execute(args, exec) {
@@ -171,6 +286,10 @@ function apply(ctx) {
171
286
  cwd = exec.agent.session.header.cwd;
172
287
  if (cwd === void 0) throw new Error("session_create needs a working directory, and this session has none");
173
288
  }
289
+ // Ask before creating anything: a session that appears in the person's
290
+ // list without them knowing about it is the whole risk of this tool.
291
+ const where = workspace === void 0 ? "ungrouped" : `in workspace ${JSON.stringify(workspace.path)}`;
292
+ await requireApproval(ctx, exec, `create a new session ${where}, starting with: ${prompt.slice(0, 120)}`);
174
293
  const agentOptions = currentSelection(ctx, exec.agent);
175
294
  const agentPresets = ctx.get("agentPresets");
176
295
  const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
@@ -183,6 +302,7 @@ function apply(ctx) {
183
302
  agentOptions,
184
303
  meta: {
185
304
  cwd,
305
+ parentSession: String(exec.agent.session.header.id),
186
306
  ...presetId === void 0 ? {} : { agentPreset: presetId }
187
307
  },
188
308
  ...agentPresets === void 0 || presetId === void 0 ? {} : { setup: async (agentCtx) => {
@@ -215,10 +335,18 @@ function apply(ctx) {
215
335
  } catch {}
216
336
  throw error;
217
337
  }
338
+ // Name the session in the receipt when its title is known yet; a session
339
+ // titled from its first message may not have one until that turn runs.
340
+ let currentTitle;
341
+ try {
342
+ // The service returns a title snapshot; the text lives on `.title`.
343
+ currentTitle = ctx.sessionTitle.get(handle.agent.session)?.title;
344
+ } catch {}
218
345
  return {
219
346
  sessionId: String(sessionId),
220
347
  grouped: workspace !== void 0,
221
348
  cwd,
349
+ ...currentTitle === void 0 || currentTitle === "" ? {} : { title: String(currentTitle) },
222
350
  ...workspace === void 0 ? {} : {
223
351
  workspaceId: String(workspace.id),
224
352
  workspacePath: workspace.path
@@ -239,6 +367,14 @@ function apply(ctx) {
239
367
  type: "string",
240
368
  required: true,
241
369
  description: "Message text. Write it self-contained: the target cannot see this conversation unless the person linked the two."
370
+ },
371
+ wait: {
372
+ type: "boolean",
373
+ description: "Wait for the target to finish working on this message before returning, and report its answer. Defaults to false: sending returns as soon as the target accepts the message. Waiting is bounded by timeoutMs."
374
+ },
375
+ timeoutMs: {
376
+ type: "number",
377
+ description: "How long to wait when wait is true, in milliseconds. Defaults to 60000, at most 300000. A timeout reports that the target is still working rather than failing."
242
378
  }
243
379
  },
244
380
  output: {
@@ -253,12 +389,20 @@ function apply(ctx) {
253
389
  cwd: {
254
390
  type: "string",
255
391
  required: true
256
- }
392
+ },
393
+ waited: { type: "boolean" },
394
+ completed: { type: "boolean" },
395
+ elapsedMs: { type: "number" },
396
+ output: { type: "string" }
257
397
  }
258
398
  },
259
399
  render: (_args, value) => [{
260
400
  type: "text",
261
- text: `Delivered to session ${value.sessionId}`
401
+ text: value.waited !== true
402
+ ? `Delivered to session ${value.sessionId}`
403
+ : value.completed === true
404
+ ? `Session ${value.sessionId} finished (${Math.round((value.elapsedMs ?? 0) / 1000)}s):\n${value.output ?? "(no text answer)"}`
405
+ : `Delivered to session ${value.sessionId}; still working after ${Math.round((value.elapsedMs ?? 0) / 1000)}s`
262
406
  }]
263
407
  },
264
408
  async execute(args, exec) {
@@ -272,6 +416,9 @@ function apply(ctx) {
272
416
  if (targetId === String(exec.agent.id)) throw new Error("session_send cannot send to its own session: use the current conversation instead");
273
417
  const depth = target.session.header.delegationDepth ?? 0;
274
418
  if (depth > 0) throw new Error(`session_send cannot send to ${JSON.stringify(targetId)}: that is a subagent session, not a regular one. Use send_message for it.`);
419
+ // Ask before writing into another session: the person should see a message
420
+ // arrive in a conversation they are not looking at.
421
+ await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(targetId)}: ${message.slice(0, 120)}`);
275
422
  target.followup(createUserMessage({
276
423
  content: [{
277
424
  type: "text",
@@ -282,10 +429,205 @@ function apply(ctx) {
282
429
  plugin: name
283
430
  }
284
431
  }));
285
- return {
432
+ if (args.wait !== true) return {
286
433
  sessionId: targetId,
287
434
  cwd: String(target.session.header.cwd ?? "")
288
435
  };
436
+ // The message is queued, so `whenIdle` settling means the target finished
437
+ // working on it. The bound is the host's own cancellable-wait shape:
438
+ // race the idle promise against a timer (dsh-schedule does the same).
439
+ const startedAt = Date.now();
440
+ const timeoutMs = waitBudgetMs(args.timeoutMs);
441
+ const timedOut = await Promise.race([
442
+ target.whenIdle().then(() => false),
443
+ new Promise((resolve) => {
444
+ setTimeout(() => resolve(true), timeoutMs);
445
+ })
446
+ ]);
447
+ const answer = await readFinalAnswer(ctx, targetId);
448
+ return {
449
+ sessionId: targetId,
450
+ cwd: String(target.session.header.cwd ?? ""),
451
+ waited: true,
452
+ completed: !timedOut,
453
+ elapsedMs: Date.now() - startedAt,
454
+ ...answer === void 0 ? {} : { output: answer }
455
+ };
456
+ }
457
+ }));
458
+ ctx.tools.register(defineTool({
459
+ name: "list_sessions",
460
+ description: "List the sessions the person can see, newest first, with the id each one carries and what it is doing right now (working, waiting, or put away). Use it before session_send when the target is described by name rather than by id, so the message goes to the right session.",
461
+ parameters: {
462
+ limit: {
463
+ type: "number",
464
+ description: "How many sessions to list, most recently active first. Defaults to 20."
465
+ }
466
+ },
467
+ output: {
468
+ schema: {
469
+ type: "object",
470
+ additionalProperties: false,
471
+ properties: {
472
+ sessions: {
473
+ type: "array",
474
+ required: true,
475
+ items: {
476
+ type: "object",
477
+ additionalProperties: false,
478
+ properties: {
479
+ sessionId: {
480
+ type: "string",
481
+ required: true
482
+ },
483
+ title: { type: "string" },
484
+ cwd: { type: "string" },
485
+ state: {
486
+ type: "string",
487
+ required: true,
488
+ enum: ["running", "idle", "archived"],
489
+ 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)."
490
+ },
491
+ current: { type: "boolean" },
492
+ subagent: { type: "boolean" }
493
+ }
494
+ }
495
+ },
496
+ total: {
497
+ type: "number",
498
+ required: true
499
+ }
500
+ }
501
+ },
502
+ render: (_args, value) => [{
503
+ type: "text",
504
+ text: value.total === 0
505
+ ? "No other sessions."
506
+ : [
507
+ value.sessions.map((entry) => [
508
+ sessionReference(entry.title, entry.sessionId),
509
+ entry.current === true ? "(this session)" : undefined,
510
+ entry.subagent === true ? "(subagent)" : undefined,
511
+ entry.state === "running" ? "(working now)" : undefined,
512
+ entry.state === "archived" ? "(put away)" : undefined,
513
+ entry.cwd
514
+ ].filter((part) => part !== undefined).join(" · ")).join("\n"),
515
+ value.sessions.some((entry) => entry.state === "archived") ? "Sessions marked (put away) are archived: they are hidden from the sidebar but still listed here." : undefined
516
+ ].filter((part) => part !== undefined).join("\n")
517
+ }]
518
+ },
519
+ async execute(args, exec) {
520
+ const query = ctx.get("sessionQuery");
521
+ if (query === void 0) throw new Error("list_sessions needs session lookup, which this DSH does not offer");
522
+ const requested = args.limit === void 0 ? 20 : Math.trunc(args.limit);
523
+ const limit = requested < 1 ? 1 : requested > 100 ? 100 : requested;
524
+ const self = exec.agent === void 0 ? undefined : String(exec.agent.id);
525
+ const records = await query.listSessions();
526
+ const listed = [];
527
+ let total = 0;
528
+ for (const record of records) {
529
+ const header = record.header;
530
+ const sessionId = String(header.id);
531
+ total += 1;
532
+ // Subagent sessions are someone else's working state, not a target the
533
+ // person can be asked about; the count still reports them.
534
+ if ((header.delegationDepth ?? 0) > 0 || header.origin === "subagent") continue;
535
+ if (listed.length >= limit) continue;
536
+ let title;
537
+ try {
538
+ // Title reads return a snapshot, not a string: the text lives on
539
+ // `.title`, exactly like the title service the create path uses.
540
+ title = (await query.readTitle(sessionId))?.title;
541
+ } catch {}
542
+ listed.push({
543
+ sessionId,
544
+ ...title === void 0 || title === "" ? {} : { title: String(title) },
545
+ ...header.cwd === void 0 ? {} : { cwd: String(header.cwd) },
546
+ state: sessionState(ctx, sessionId),
547
+ ...sessionId === self ? { current: true } : {}
548
+ });
549
+ }
550
+ return { sessions: listed, total };
551
+ }
552
+ }));
553
+ ctx.tools.register(defineTool({
554
+ name: "session_wait",
555
+ description: "Wait for another chat session to finish what it is doing and report its answer. Use it after session_send to hear back, or on its own when the person asks how another session is getting on. It only reads: it never opens, changes, or interrupts a session, and a session that is not running returns immediately.",
556
+ parameters: {
557
+ sessionId: {
558
+ type: "string",
559
+ required: true,
560
+ description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
561
+ },
562
+ timeoutMs: {
563
+ type: "number",
564
+ description: "How long to wait, in milliseconds. Defaults to 60000, at most 300000. A timeout reports that the session is still working rather than failing."
565
+ }
566
+ },
567
+ output: {
568
+ schema: {
569
+ type: "object",
570
+ additionalProperties: false,
571
+ properties: {
572
+ sessionId: {
573
+ type: "string",
574
+ required: true
575
+ },
576
+ running: {
577
+ type: "boolean",
578
+ required: true
579
+ },
580
+ completed: {
581
+ type: "boolean",
582
+ required: true
583
+ },
584
+ elapsedMs: { type: "number" },
585
+ output: { type: "string" }
586
+ }
587
+ },
588
+ render: (_args, value) => [{
589
+ type: "text",
590
+ text: value.running !== true || value.completed === true
591
+ ? `Session ${value.sessionId} is not working on anything${value.output === undefined ? "" : `; its answer:\n${value.output}`}`
592
+ : `Session ${value.sessionId} is still working after ${Math.round((value.elapsedMs ?? 0) / 1000)}s`
593
+ }]
594
+ },
595
+ async execute(args, exec) {
596
+ const requested = args.sessionId.trim();
597
+ if (requested === "") throw new Error("session_wait needs a session id");
598
+ if (exec.agent !== void 0 && requested === String(exec.agent.id)) throw new Error("session_wait cannot wait on its own session: that would wait for the answer it is writing");
599
+ const target = ctx.agents.get(requested);
600
+ if (target === void 0) {
601
+ // Not running: nothing to wait for. Confirm the id exists at all so a
602
+ // typo is reported instead of looking like an idle session.
603
+ const query = ctx.get("sessionQuery");
604
+ if (query === void 0) throw new Error(`session_wait cannot check ${JSON.stringify(requested)}: this DSH does not offer session lookup`);
605
+ const known = (await query.listSessions()).some((entry) => String(entry.header.id) === requested);
606
+ if (!known) throw new Error(`session_wait cannot find session ${JSON.stringify(requested)}: no open or saved session has that id`);
607
+ const answer = await readFinalAnswer(ctx, requested);
608
+ return {
609
+ sessionId: requested,
610
+ running: false,
611
+ completed: true,
612
+ elapsedMs: 0,
613
+ ...answer === void 0 ? {} : { output: answer }
614
+ };
615
+ }
616
+ const startedAt = Date.now();
617
+ const timedOut = await Promise.race([
618
+ target.whenIdle().then(() => false),
619
+ new Promise((resolve) => {
620
+ setTimeout(() => resolve(true), waitBudgetMs(args.timeoutMs));
621
+ })
622
+ ]);
623
+ const answer = await readFinalAnswer(ctx, requested);
624
+ return {
625
+ sessionId: requested,
626
+ running: true,
627
+ completed: !timedOut,
628
+ elapsedMs: Date.now() - startedAt,
629
+ ...answer === void 0 ? {} : { output: answer }
630
+ };
289
631
  }
290
632
  }));
291
633
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ryuu-64/dsh-session-tools",
3
- "version": "0.4.2",
4
- "description": "Let the agent start a new chat session, or send a message to another one.",
3
+ "version": "0.5.3",
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",
7
7
  "keywords": [
@@ -18,11 +18,20 @@
18
18
  "main": "lib/index.js",
19
19
  "exports": {
20
20
  ".": "./lib/index.js",
21
+ "./client": "./lib/client.js",
21
22
  "./package.json": "./package.json"
22
23
  },
23
24
  "dsh": {
24
25
  "bundle": {
25
26
  "patch": "./cordis.patch.yml"
27
+ },
28
+ "client": {
29
+ "platform": "web",
30
+ "inject": [
31
+ "@deepseek-ai/dsh-client-runtime",
32
+ "@deepseek-ai/dsh-client-ui-slots",
33
+ "@deepseek-ai/dsh-client-ui-tool"
34
+ ]
26
35
  }
27
36
  },
28
37
  "publishConfig": {
@@ -38,7 +47,8 @@
38
47
  "@deepseek-ai/dsh-session-title": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
39
48
  "@deepseek-ai/dsh-tools": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
40
49
  "@deepseek-ai/dsh-workspace": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
41
- "@deepseek-ai/schemastery": "^3.18.2"
50
+ "@deepseek-ai/schemastery": "^3.18.2",
51
+ "react": ">=18 <20"
42
52
  },
43
53
  "files": [
44
54
  "lib",