@ryuu-64/dsh-session-tools 0.8.0 → 0.8.1

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/lib/index.js CHANGED
@@ -1,894 +1,906 @@
1
- import { setTimeout as delay } from "node:timers/promises";
2
- import { randomUUID } from "node:crypto";
3
- import { isAbsolute } from "node:path";
4
- import z from "@deepseek-ai/schemastery";
5
- import { defineTool } from "@deepseek-ai/dsh-tools";
6
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
- import { brandString } from "@deepseek-ai/dsh-brand";
8
- import { symbols } from "@deepseek-ai/cordis";
9
- import { fallbackSessionTitle } from "@deepseek-ai/dsh-session-title";
10
- import { receiptProjection, receiptProjectionKey, foldReceipts, messageReceipt } from "./message-receipts.js";
11
- import { createActivitySorter, readSlots } from "./session-activity.js";
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";
15
-
16
- /** Stable Loader identity and producer-owned message source (V3 and V4). */
17
- const name = "tool-session";
18
- /** Nothing to configure. */
19
- const Config = z.object({});
20
- // Public fallback helper, using the shipped dsh-base 0.1.5-rc.2 limits.
21
- // SessionTitleService.rename still enforces the host's accepted-title limit.
22
- const fallbackTitleWords = 5;
23
- const fallbackTitleBytes = 40;
24
- /** Host services this tool needs: where it registers tools, and what it creates a session with. */
25
- const inject = [
26
- "tools",
27
- "agents",
28
- "sessionTitle",
29
- "workspaceRegistry",
30
- "agentDefaultModel",
31
- "storageDomain"
32
- ];
33
- /** List the existing workspaces, so a rejected path tells the caller what to use instead. */
34
- function workspaceCatalogue(registry) {
35
- const items = registry.list();
36
- return items.map((workspace) => `${workspace.title} (${workspace.path})`).join("; ");
37
- }
38
- /**
39
- * Name a session in tool output, the way a person would say it: the title they
40
- * will see in the sidebar, plus the id when the title is not known yet.
41
- *
42
- * Deliberately NOT the `@[label](dsh-session:…)` mention form. That form renders
43
- * as a chip in message text but carries no navigation — it is a label, not a
44
- * link — and whether it renders at all depends on machinery a tool result does
45
- * not have. A receipt should read the same everywhere.
46
- * @param title - the session's title, when it is known yet.
47
- * @param sessionId - the session's id.
48
- * @returns one line naming the session.
49
- */
50
- function sessionReference(title, sessionId) {
51
- // Title reads hand back a snapshot, not a string; take the text either way so
52
- // a receipt can never print an object.
53
- const raw = typeof title === "object" && title !== null ? title.title : title;
54
- const label = typeof raw === "string" ? raw.trim() : "";
55
- return label === "" ? sessionId : `${label} · ${sessionId}`;
56
- }
57
- /**
58
- * Ask before touching another session, except for the explicit full-access
59
- * preset. Sandbox and approval are independent policies: `never` alone denies
60
- * approval requests, it does not grant permission.
61
- * @param ctx - services of the calling agent.
62
- * @param exec - the running tool execution, including its cancellation signal.
63
- * @param reason - what is about to happen, in the person's own terms.
64
- * @throws when permission cannot be established or the request is not allowed.
65
- */
66
- async function requireApproval(ctx, exec, reason) {
67
- const cancelled = () => {
68
- if (exec.signal?.aborted) throw new Error(`the tool was cancelled, so ${reason} was not done`);
69
- };
70
- cancelled();
71
- const approval = ctx.get("approval");
72
- const sandboxPolicy = ctx.get("sandboxPolicy");
73
- if (typeof approval?.overrideOf !== "function" || typeof approval?.request !== "function" || typeof sandboxPolicy?.resolve !== "function") {
74
- throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
75
- }
76
- const session = exec.agent.session;
77
- const mode = sandboxPolicy.resolve({ session })?.mode;
78
- const policy = approval.overrideOf(session) ?? approval.config?.policy ?? "ask";
79
- if (!["read-only", "workspace-write", "danger-full-access"].includes(mode) || !["ask", "never"].includes(policy)) {
80
- throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
81
- }
82
- cancelled();
83
- if (mode === "danger-full-access" && policy === "never") return;
84
- const outcome = await approval.request({
85
- agent: exec.agent,
86
- toolName: exec.name,
87
- callId: exec.callId,
88
- reason,
89
- signal: exec.signal
90
- });
91
- // A late answer must not revive a tool execution that has been cancelled.
92
- cancelled();
93
- if (outcome === "allowed-once") return;
94
- throw new Error(
95
- outcome === "rejected"
96
- ? `the person declined: ${reason} was not done`
97
- : `no answer to the approval request, so ${reason} was not done (${outcome})`
98
- );
99
- }
100
- /**
101
- * Give the new session the same model as this one: read the model the calling
102
- * session is using, and fall back to the default when it has not chosen one.
103
- */
104
- function currentSelection(ctx, agent) {
105
- const projections = ctx.get("sessionProjections");
106
- let inherited;
107
- if (projections !== void 0) try {
108
- const state = projections.stateOf(agent.session, "modelSelection");
109
- inherited = state?.pending ?? state?.lastUsed ?? void 0;
110
- } catch {}
111
- if (inherited !== void 0) return {
112
- provider: inherited.provider,
113
- model: inherited.model,
114
- ...inherited.reasoningEffort === void 0 ? {} : { reasoningEffort: inherited.reasoningEffort }
115
- };
116
- const selected = ctx.agentDefaultModel.currentSelection();
117
- return {
118
- provider: selected.provider,
119
- model: selected.model
120
- };
121
- }
122
- /**
123
- * Find the agent preset the new session should start on: the one this session
124
- * uses, or the default preset when this session has none. A new session without
125
- * a preset gets no tools, so it would sit in the list unable to do anything.
126
- * @param ctx - services of the calling agent.
127
- * @param agent - the calling agent.
128
- * @param presets - the preset registry, when one is composed.
129
- * @returns the preset id to use, or undefined when there is none.
130
- */
131
- async function resolvePreset(ctx, agent, presets) {
132
- const projections = ctx.get("sessionProjections");
133
- if (projections !== void 0) try {
134
- const current = projections.stateOf(agent.session, "agentPreset");
135
- if (current !== void 0) return current;
136
- } catch {}
137
- if (presets === void 0) return void 0;
138
- try {
139
- return (await presets.resolve(void 0)).id;
140
- } catch {
141
- return void 0;
142
- }
143
- }
144
- /**
145
- * Bound a wait request to a usable budget: a missing or nonsensical value falls
146
- * back to the default, and the ceiling keeps one tool call from hanging a turn
147
- * forever. A timeout is reported, never treated as an error.
148
- * @param requested - the caller's requested budget in milliseconds, if any.
149
- * @returns the budget actually used.
150
- */
151
- function waitBudgetMs(requested) {
152
- const DEFAULT_MS = 60_000;
153
- const MAX_MS = 300_000;
154
- if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return DEFAULT_MS;
155
- return Math.max(1, Math.min(Math.trunc(requested), MAX_MS));
156
- }
157
- /** Own only this observation: never forward its abort signal to a target agent. */
158
- async function observeWait(requested, callerSignal, observe) {
159
- const startedAt = Date.now();
160
- const controller = new AbortController();
161
- const cleanups = new Set();
162
- const stopped = Promise.withResolvers();
163
- let status;
164
- const stop = (reason) => {
165
- if (status !== undefined) return;
166
- status = reason;
167
- stopped.resolve({ waitStatus: reason, completed: false });
168
- controller.abort();
169
- };
170
- const onAbort = () => stop("callerCancelled");
171
- let timer;
172
- try {
173
- callerSignal?.addEventListener("abort", onAbort, { once: true });
174
- if (callerSignal?.aborted) onAbort();
175
- else timer = setTimeout(() => stop("timedOut"), waitBudgetMs(requested));
176
- const result = await Promise.race([
177
- stopped.promise,
178
- (async () => {
179
- controller.signal.throwIfAborted();
180
- const value = await observe(controller.signal, (cleanup) => cleanups.add(cleanup));
181
- controller.signal.throwIfAborted();
182
- return { waitStatus: "completed", completed: true, ...value };
183
- })()
184
- ]);
185
- return { ...result, elapsedMs: Date.now() - startedAt };
186
- } finally {
187
- clearTimeout(timer);
188
- callerSignal?.removeEventListener("abort", onAbort);
189
- // This also releases an outstanding polling timer or cancellable log read.
190
- controller.abort();
191
- await Promise.all([...cleanups].map(cleanup => cleanup()));
192
- }
193
- }
194
-
195
- /** Snapshot the delivery itself, including reentrant claims/removals in followup. */
196
- function deliveredReceipt(agent, messageId) {
197
- try {
198
- const events = agent.session.snapshotEvents?.();
199
- if (events !== undefined) {
200
- const result = messageReceipt(foldReceipts(events, agent.session.inheritedEventCount), messageId, events);
201
- if (result.messageStatus !== "unknown") return result;
202
- }
203
- if ([agent.inbox?.nextTurn, agent.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) return { messageStatus: "queued", completed: false };
204
- } catch {}
205
- return { messageStatus: "unknown", completed: false, attributionNote: "Delivery returned, but this host does not provide reliable message attribution." };
206
- }
207
-
208
- /** Read one exact message receipt. Quiet or a missing queue entry proves nothing. */
209
- async function waitForReceipt(ctx, sessionId, messageId, signal, onCleanup, onProgress) {
210
- for (;;) {
211
- signal.throwIfAborted();
212
- const log = await readSessionLog(ctx, sessionId, signal, onCleanup);
213
- const target = ctx.agents.get(sessionId);
214
- const cached = log.session !== undefined && target?.session === log.session ? ctx.get?.("sessionProjections")?.stateOf?.(log.session, receiptProjectionKey) : undefined;
215
- const state = cached !== undefined && cached.seq === (log.events.at(-1)?.seq ?? -1) ? cached : foldReceipts(log.events, log.inheritedEventCount);
216
- let value = messageReceipt(state, messageId, log.events);
217
- // Pending live input is positive queue evidence even on a host without
218
- // durable inbox events. Its later disappearance will NEVER imply success.
219
- if (value.messageStatus === "unknown" && [target?.inbox?.nextTurn, target?.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) {
220
- value = { messageStatus: "queued", completed: false };
221
- }
222
- if (target === undefined && ["queued", "delivered"].includes(value.messageStatus)) value = { ...value, attributionNote: "The saved message has no recorded turn result. This read does not resume the target." };
223
- onProgress(value);
224
- if (!["queued", "delivered"].includes(value.messageStatus) || target === undefined) return value;
225
- await delay(25, undefined, { signal });
226
- }
227
- }
228
-
229
- /** Preserve the last receipt state on timeout/caller cancellation, never its output. */
230
- async function observeReceipt(ctx, sessionId, messageId, requested, callerSignal) {
231
- let latest = { messageStatus: "unknown", completed: false };
232
- const result = await observeWait(requested, callerSignal, (signal, onCleanup) =>
233
- waitForReceipt(ctx, sessionId, messageId, signal, onCleanup, value => { latest = value; }));
234
- if (result.waitStatus === "completed") return result;
235
- const { output, ...receipt } = latest;
236
- return { ...receipt, ...result };
237
- }
238
-
239
- const receiptProperties = {
240
- messageId: { type: "string" },
241
- messageStatus: { type: "string", enum: ["queued", "delivered", "turnCompleted", "discarded", "cancelled", "blocked", "failed", "interrupted", "incomplete", "unknown"] },
242
- turn: { type: "number" },
243
- turnEndKind: { type: "string" },
244
- attributionNote: { type: "string" },
245
- output: { type: "string" }
246
- };
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
- };
256
- function receiptText(value) {
257
- const receipt = `Receipt: sessionId=${value.sessionId}, messageId=${value.messageId}`;
258
- const notice = waitNotice(value);
259
- return `${statusLabels[value.messageStatus] ?? "暂无法确认"}\n${receipt}` +
260
- (value.attributionNote ? `\n${value.attributionNote}` : "") + (notice ? `\n${notice}` : "") +
261
- (value.output === undefined ? "" : `\n${value.output}`);
262
- }
263
-
264
- /** A stopped observation says nothing about the target task's final outcome. */
265
- function waitNotice(value) {
266
- if (value.waitStatus === "callerCancelled") return "Waiting cancelled by the caller; the target task was not cancelled.";
267
- if (value.waitStatus === "timedOut") return "Wait timed out; the target task was not cancelled. " + (value.messageId === undefined ? "Query this session overview again later." : "Query again with the same sessionId and messageId receipt; do not resend.");
268
- return undefined;
269
- }
270
-
271
- /** Read a live snapshot or a cancellable, read-only persistence handle. */
272
- async function readSessionLog(ctx, sessionId, signal, onCleanup = () => {}) {
273
- signal?.throwIfAborted();
274
- const live = ctx.agents.get(sessionId);
275
- const own = typeof live?.session?.snapshotEvents === "function" ? live.session.snapshotEvents() : undefined;
276
- let log = own === undefined ? undefined : { events: own, inheritedEventCount: live.session.inheritedEventCount ?? 0, session: live.session };
277
- if (log === undefined) {
278
- const persistence = ctx.get("sessionPersistence");
279
- if (persistence !== undefined) {
280
- // rc.2 query.readSession has no cancellation argument. Own a read-only
281
- // persistence handle instead, never a resumed/writable target agent.
282
- const reader = await persistence.open(sessionId, "read", { signal });
283
- let closing;
284
- const close = () => closing ??= Promise.resolve().then(() => reader.close());
285
- onCleanup(close);
286
- try {
287
- signal?.throwIfAborted();
288
- log = { ...await reader.read(undefined, undefined, { signal }), inheritedEventCount: reader.inheritedEventCount ?? 0 };
289
- } finally {
290
- await close();
291
- }
292
- } else {
293
- const query = ctx.get("sessionQuery");
294
- if (query === undefined) throw new Error(`this DSH cannot read session ${JSON.stringify(sessionId)}`);
295
- // Compatibility with hosts exposing only the query service: the outer
296
- // observation remains bounded, but that service owns its read lifetime.
297
- log = await query.readSession(sessionId);
298
- }
299
- signal?.throwIfAborted();
300
- }
301
- return log;
302
- }
303
-
304
- /** Session-only overview, explicitly not a message result. */
305
- async function readFinalAnswer(ctx, sessionId, signal, onCleanup) {
306
- const { events } = await readSessionLog(ctx, sessionId, signal, onCleanup);
307
- const texts = (content) => (content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("");
308
- let answer;
309
- const accumulated = [];
310
- for (const event of events) {
311
- if (event.type !== "assistant/message") continue;
312
- const text = texts(event.data.message?.content);
313
- if (text.trim() !== "") answer = text;
314
- else accumulated.push(text);
315
- }
316
- const found = answer ?? (accumulated.length === 0 ? undefined : accumulated.join(""));
317
- return found === undefined || found.trim() === "" ? undefined : found;
318
- }
319
- /**
320
- * Report what a session is doing right now: working, waiting, or put away. The
321
- * archive set lives on the workspace registry and answers whether the person has
322
- * hidden the session from the sidebar, so it needs no log read of its own.
323
- * @param ctx - services of the calling agent.
324
- * @param sessionId - the session to describe.
325
- * @returns `"running"`, `"archived"`, or `"idle"`.
326
- */
327
- function sessionState(ctx, sessionId) {
328
- if (ctx.get("workspaceRegistry")?.archivedSessionIds?.some((id) => String(id) === sessionId) === true) return "archived";
329
- return ctx.agents.get(sessionId)?.status === "running" ? "running" : "idle";
330
- }
331
- /** Pending resumes are shared by plugin instances using the same agent service. */
332
- const targetResumes = new WeakMap();
333
-
334
- function checkSendTarget(sessionId, header, callerAgent) {
335
- if (sessionId === String(callerAgent.id) || sessionId === String(callerAgent.session?.header.id)) throw new Error("session_send cannot send to its own session: use the current conversation instead");
336
- if ((header.delegationDepth ?? 0) > 0) throw new Error(`session_send cannot send to ${JSON.stringify(sessionId)}: that is a subagent session, not a regular one. Use send_message for it.`);
337
- if (typeof header.cwd !== "string" || header.cwd.trim() === "") throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: this saved session does not record a working directory, and reopening it needs one. Send to a session that has a directory, or ask the person to open that session once.`);
338
- }
339
-
340
- /** Read target metadata without opening a writable session or publishing an agent. */
341
- async function inspectSendTarget(ctx, sessionId, exec) {
342
- exec.signal?.throwIfAborted();
343
- if (sessionId === String(exec.agent.id) || sessionId === String(exec.agent.session?.header.id)) throw new Error("session_send cannot send to its own session: use the current conversation instead");
344
- const live = ctx.agents.get(sessionId);
345
- if (live !== void 0) {
346
- checkSendTarget(sessionId, live.session.header, exec.agent);
347
- return { agent: live, header: live.session.header };
348
- }
349
- const query = ctx.get("sessionQuery");
350
- if (query === void 0) throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: this DSH does not offer session lookup`);
351
- let record;
352
- try {
353
- // listSessions owns and releases its read resources; no handle escapes.
354
- record = (await query.listSessions(exec.signal)).find((entry) => String(entry.header.id) === sessionId);
355
- } catch (error) {
356
- throw new Error(`session_send cannot read ${JSON.stringify(sessionId)}: ${error instanceof Error ? error.message : String(error)}`);
357
- }
358
- exec.signal?.throwIfAborted();
359
- if (record === void 0) throw new Error(`session_send cannot find session ${JSON.stringify(sessionId)}: no open or saved session has that id`);
360
- checkSendTarget(sessionId, record.header, exec.agent);
361
- return { header: record.header };
362
- }
363
-
364
- /** Recheck after approval, then serialize resumes so concurrent sends share one agent. */
365
- async function resolveTargetAgent(ctx, sessionId, exec) {
366
- const agents = ctx.agents;
367
- // Cordis creates a fresh traced proxy on each service read. Its exported
368
- // original symbol gives stable identity; keep using the traced service for
369
- // method calls so ownership and caller context are still preserved.
370
- const serviceIdentity = agents[symbols.original] ?? agents;
371
- let pending = targetResumes.get(serviceIdentity);
372
- if (pending === void 0) targetResumes.set(serviceIdentity, pending = new Map());
373
- const previous = pending.get(sessionId);
374
- const operation = (async () => {
375
- // A failed/cancelled earlier sender must not invalidate this sender's grant.
376
- if (previous !== void 0) await previous.catch(() => {});
377
- const inspected = await inspectSendTarget(ctx, sessionId, exec);
378
- exec.signal?.throwIfAborted();
379
- // Another host caller may have published the agent during the metadata read.
380
- const live = agents.get(sessionId);
381
- if (live !== void 0) {
382
- checkSendTarget(sessionId, live.session.header, exec.agent);
383
- return live;
384
- }
385
- const agentPresets = ctx.get("agentPresets");
386
- const presetId = inspected.header.agentPreset;
387
- const setup = agentPresets === void 0 || presetId === void 0 ? void 0 : async (agentCtx) => {
388
- await agentPresets.mount(agentCtx, presetId);
389
- };
390
- const resumed = await agents.resume({
391
- resumeSessionId: sessionId,
392
- agentOptions: currentSelection(ctx, exec.agent),
393
- signal: exec.signal,
394
- ...setup === void 0 ? {} : { setup }
395
- });
396
- return resumed.agent;
397
- })();
398
- pending.set(sessionId, operation);
399
- const release = () => {
400
- if (pending.get(sessionId) === operation) pending.delete(sessionId);
401
- };
402
- // Keep the queue slot until the actual operation settles, even if this
403
- // caller stops waiting. Otherwise a later sender could bypass an active resume.
404
- void operation.then(release, release);
405
- if (previous !== void 0 && exec.signal !== void 0) {
406
- const cancelled = Promise.withResolvers();
407
- const onAbort = () => cancelled.reject(exec.signal.reason);
408
- try {
409
- exec.signal.addEventListener("abort", onAbort, { once: true });
410
- if (exec.signal.aborted) onAbort();
411
- await Promise.race([previous.catch(() => {}), cancelled.promise]);
412
- } finally {
413
- exec.signal.removeEventListener("abort", onAbort);
414
- }
415
- }
416
- return await operation;
417
- }
418
- /**
419
- * Register `session_create` and `session_send`.
420
- * @param ctx - services of the agent this plugin was loaded for.
421
- */
422
- function apply(ctx) {
423
- const permissions = communicationPermissions(ctx);
424
- ctx.inject(["typert", "connection"], scope => { scope.plugin(CommunicationRemote); });
425
- const inSlot = readSlots();
426
- const sortByActivity = createActivitySorter(ctx, inSlot);
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
- }));
462
- // Optional capability; the same pure fold also works over a read-only full log.
463
- if (typeof ctx.inject === "function") ctx.inject(["sessionProjections"], scope => {
464
- scope.sessionProjections.register(receiptProjection);
465
- });
466
- ctx.tools.register(defineTool({
467
- name: "session_create",
468
- description: "Start a new chat session the person can see in the session list. The new session runs its own first turn and keeps going on its own; this call returns as soon as it exists. Pass workspacePath to put it under that workspace, or leave it out to leave it ungrouped. Use this when the work deserves its own session the person can open and continue; use a subagent instead when the work should stay inside this conversation.",
469
- parameters: {
470
- prompt: {
471
- type: "string",
472
- required: true,
473
- description: "The new session's first task, delivered with plugin provenance. Write it self-contained: the new session cannot see this conversation."
474
- },
475
- workspacePath: {
476
- type: "string",
477
- description: "Full path of a workspace that already exists (for example \"E:\\\\Users\\\\Ryuu\\\\Desktop\"). Leave it out to leave the new session ungrouped. This tool never creates a workspace, so an unknown path fails with the list of existing ones."
478
- },
479
- title: {
480
- type: "string",
481
- description: "Optional fixed title. If omitted or blank, derive it once from the prompt using the host's public normalization and truncation rules (first 5 whitespace-delimited words, at most 40 UTF-8 bytes). No extra model call; later messages do not automatically rename it. The person can still rename it manually."
482
- },
483
- wait: {
484
- type: "boolean",
485
- description: "Wait for the first message's recorded turn to end before returning. Defaults to false; bounded by timeoutMs."
486
- },
487
- timeoutMs: {
488
- type: "number",
489
- description: "Wait budget in milliseconds. Defaults to 60000, at most 300000. Timeout or caller cancellation only ends this wait."
490
- }
491
- },
492
- output: {
493
- schema: {
494
- type: "object",
495
- additionalProperties: false,
496
- properties: {
497
- sessionId: {
498
- type: "string",
499
- required: true
500
- },
501
- grouped: {
502
- type: "boolean",
503
- required: true
504
- },
505
- cwd: {
506
- type: "string",
507
- required: true
508
- },
509
- workspaceId: { type: "string" },
510
- workspacePath: { type: "string" },
511
- title: { type: "string" },
512
- waited: { type: "boolean" },
513
- completed: { type: "boolean" },
514
- waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
515
- elapsedMs: { type: "number" },
516
- ...receiptProperties
517
- }
518
- },
519
- // rc.2 persists this projection on tool/result and exposes it as
520
- // ToolResultNode.meta. The canonical value alone does not survive replay.
521
- presentationMeta: (_args, value) => ({
522
- sessionId: value.sessionId,
523
- ...receiptMeta(value),
524
- ...typeof value.title === "string" ? { title: value.title } : {}
525
- }),
526
- // Keep the receipt readable for clients without the session card.
527
- render: (_args, value) => [{
528
- type: "text",
529
- text: (value.grouped === true
530
- ? `Created session: ${sessionReference(value.title, value.sessionId)} in workspace ${value.workspacePath}`
531
- : `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`) + `\n${receiptText(value)}`
532
- }]
533
- },
534
- async execute(args, exec) {
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);
538
- const prompt = args.prompt.trim();
539
- if (prompt === "") throw new Error("session_create needs a prompt: it becomes the new session's first user message");
540
- let workspace;
541
- let cwd;
542
- if (args.workspacePath !== void 0) {
543
- const requested = args.workspacePath.trim();
544
- if (!isAbsolute(requested)) throw new Error(`session_create needs a full workspace path, got ${JSON.stringify(args.workspacePath)}`);
545
- workspace = await ctx.workspaceRegistry.resolveByPath(requested);
546
- if (workspace === void 0) {
547
- throw new Error(`session_create cannot use ${JSON.stringify(requested)}: no workspace has that path, and this tool does not create workspaces. Existing workspaces: ${workspaceCatalogue(ctx.workspaceRegistry)}. Use one of those paths, or leave workspacePath out to create the session under Ungrouped.`);
548
- }
549
- cwd = workspace.path;
550
- } else {
551
- cwd = exec.agent.session.header.cwd;
552
- if (cwd === void 0) throw new Error("session_create needs a working directory, and this session has none");
553
- }
554
- // Ask before creating anything: a session that appears in the person's
555
- // list without them knowing about it is the whole risk of this tool.
556
- const where = workspace === void 0 ? "ungrouped" : `in workspace ${JSON.stringify(workspace.path)}`;
557
- await permissions.check(sourceId);
558
- await requireApproval(ctx, exec, `create a new session ${where}, starting with: ${prompt.slice(0, 120)}`);
559
- await permissions.check(sourceId);
560
- const agentOptions = currentSelection(ctx, exec.agent);
561
- const agentPresets = ctx.get("agentPresets");
562
- const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
563
- exec.signal?.throwIfAborted();
564
- const sessionId = brandString(`session-${randomUUID()}`);
565
- let handle;
566
- let attached = false;
567
- let sent;
568
- try {
569
- handle = await ctx.agents.create({
570
- signal: exec.signal,
571
- sessionId,
572
- agentOptions,
573
- meta: {
574
- cwd,
575
- parentSession: String(exec.agent.session.header.id),
576
- ...presetId === void 0 ? {} : { agentPreset: presetId }
577
- },
578
- ...agentPresets === void 0 || presetId === void 0 ? {} : { setup: async (agentCtx) => {
579
- await agentPresets.mount(agentCtx, presetId);
580
- } }
581
- });
582
- exec.signal?.throwIfAborted();
583
- if (workspace !== void 0) {
584
- await workspace.attachSession(sessionId);
585
- attached = true;
586
- }
587
- exec.signal?.throwIfAborted();
588
- const title = args.title?.trim() || fallbackSessionTitle(prompt, fallbackTitleWords, fallbackTitleBytes);
589
- // The public rename operation logs and pins the initial title. It
590
- // does not change the first message's plugin provenance below.
591
- ctx.sessionTitle.rename(handle.agent.session, title);
592
- exec.signal?.throwIfAborted();
593
- sent = createUserMessage({
594
- content: [{
595
- type: "text",
596
- text: prompt
597
- }],
598
- source: {
599
- kind: name,
600
- form: "relay"
601
- }
602
- });
603
- await permissions.admit(sourceId, String(sessionId), exec, () => handle.agent.followup(sent));
604
- } catch (error) {
605
- if (attached) try {
606
- await workspace.detachSession(sessionId);
607
- } catch {}
608
- if (handle !== void 0) try {
609
- await handle.dispose();
610
- } catch {}
611
- throw error;
612
- }
613
- // Once delivered, the target owns its lifetime. Ending this observation
614
- // must not detach its workspace or dispose its handle.
615
- const waited = args.wait === true ? await observeReceipt(ctx, String(sessionId), sent.id, args.timeoutMs, exec.signal) : undefined;
616
- // Read the accepted title after host normalization (or a manual rename).
617
- let currentTitle;
618
- try {
619
- // The service returns a title snapshot; the text lives on `.title`.
620
- currentTitle = ctx.sessionTitle.get(handle.agent.session)?.title;
621
- } catch {}
622
- return {
623
- sessionId: String(sessionId),
624
- messageId: sent.id,
625
- ...waited === undefined ? deliveredReceipt(handle.agent, sent.id) : { waited: true, ...waited },
626
- grouped: workspace !== void 0,
627
- cwd,
628
- ...currentTitle === void 0 || currentTitle === "" ? {} : { title: String(currentTitle) },
629
- ...workspace === void 0 ? {} : {
630
- workspaceId: String(workspace.id),
631
- workspacePath: workspace.path
632
- }
633
- };
634
- }
635
- }));
636
- ctx.tools.register(defineTool({
637
- name: "session_send",
638
- description: "Send a message to an existing chat session so that session continues on its own — including one this session started earlier. It cannot send to itself, cannot send to a subagent the agent spawned (use send_message for those), and never rewrites past messages. Sending returns right away; the target handles the message when it can.",
639
- parameters: {
640
- sessionId: {
641
- type: "string",
642
- required: true,
643
- description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
644
- },
645
- message: {
646
- type: "string",
647
- required: true,
648
- description: "Message text. Write it self-contained: the target cannot see this conversation unless the person linked the two."
649
- },
650
- wait: {
651
- type: "boolean",
652
- 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."
653
- },
654
- timeoutMs: {
655
- type: "number",
656
- description: "How long to observe this receipt when wait is true, in milliseconds. Defaults to 60000, at most 300000. Timeout never proves success or failure and never resends or cancels the target."
657
- }
658
- },
659
- output: {
660
- schema: {
661
- type: "object",
662
- additionalProperties: false,
663
- properties: {
664
- sessionId: {
665
- type: "string",
666
- required: true
667
- },
668
- cwd: {
669
- type: "string",
670
- required: true
671
- },
672
- waited: { type: "boolean" },
673
- completed: { type: "boolean" },
674
- waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
675
- elapsedMs: { type: "number" },
676
- ...receiptProperties
677
- }
678
- },
679
- presentationMeta: (_args, value) => receiptMeta(value),
680
- render: (_args, value) => [{
681
- type: "text",
682
- text: receiptText(value)
683
- }]
684
- },
685
- async execute(args, exec) {
686
- if (exec.agent === void 0) throw new Error("session_send must run inside a session");
687
- const sourceId = trustedSource(exec);
688
- const requested = args.sessionId.trim();
689
- if (requested === "") throw new Error("session_send needs a session id");
690
- const message = args.message.trim();
691
- if (message === "") throw new Error("session_send needs a message");
692
- await permissions.check(sourceId, requested);
693
- await inspectSendTarget(ctx, requested, exec);
694
- await permissions.check(sourceId, requested);
695
- await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(requested)}: ${message.slice(0, 120)}`);
696
- await permissions.check(sourceId, requested);
697
- const target = await resolveTargetAgent(ctx, requested, exec);
698
- exec.signal?.throwIfAborted();
699
- const targetId = String(target.id);
700
- if (targetId !== requested) throw new Error("session_send resolved a different target; no message was sent");
701
- checkSendTarget(targetId, target.session.header, exec.agent);
702
- const sent = createUserMessage({
703
- content: [{
704
- type: "text",
705
- text: message
706
- }],
707
- source: {
708
- kind: name,
709
- form: "relay"
710
- }
711
- });
712
- await permissions.admit(sourceId, targetId, exec, () => target.followup(sent));
713
- if (args.wait !== true) return {
714
- sessionId: targetId,
715
- messageId: sent.id,
716
- ...deliveredReceipt(target, sent.id),
717
- cwd: String(target.session.header.cwd ?? "")
718
- };
719
- const result = await observeReceipt(ctx, targetId, sent.id, args.timeoutMs, exec.signal);
720
- return {
721
- sessionId: targetId,
722
- messageId: sent.id,
723
- cwd: String(target.session.header.cwd ?? ""),
724
- waited: true,
725
- ...result
726
- };
727
- }
728
- }));
729
- ctx.tools.register(defineTool({
730
- name: "list_sessions",
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.",
732
- parameters: {
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." },
734
- workspaceId: { type: "string", description: "Existing workspace ID (at most 256 UTF-8 bytes); mutually exclusive with workspacePath. Uses actual workspace membership." },
735
- workspacePath: { type: "string", description: "Absolute path of an existing registered workspace (at most 4096 UTF-8 bytes); mutually exclusive with workspaceId." },
736
- cursor: { type: "string", description: "Opaque nextCursor from this caller's previous page. Omit filters to inherit them; explicit filters must match. Expires after 5 minutes; no cursor starts a fresh query." },
737
- limit: {
738
- type: "number",
739
- description: "How many sessions to list, most recently active first. Defaults to 20, capped at 100. May change between pages."
740
- }
741
- },
742
- output: {
743
- schema: {
744
- type: "object",
745
- additionalProperties: false,
746
- properties: {
747
- sessions: {
748
- type: "array",
749
- required: true,
750
- items: {
751
- type: "object",
752
- additionalProperties: false,
753
- properties: {
754
- sessionId: {
755
- type: "string",
756
- required: true
757
- },
758
- title: { type: "string" },
759
- cwd: { type: "string" },
760
- state: {
761
- type: "string",
762
- required: true,
763
- enum: ["running", "idle", "archived"],
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)."
765
- },
766
- current: { type: "boolean" },
767
- subagent: { type: "boolean" },
768
- communication: { ...communicationStatusSchema, required: true }
769
- }
770
- }
771
- },
772
- matchedTotal: { type: "number", required: true, description: "Ordinary sessions matching the initial successful scan, before limit; frozen across pages." },
773
- nextCursor: { type: "string" },
774
- resultSetCreatedAt: { type: "number", description: "Result set creation time in Unix milliseconds; not an atomic database snapshot." },
775
- resultSetExpiresAt: { type: "number", description: "Fixed expiration time in Unix milliseconds." },
776
- paginationUnavailable: { type: "string" },
777
- workspaceId: { type: "string" },
778
- workspacePath: { type: "string" },
779
- total: {
780
- type: "number",
781
- required: true
782
- }
783
- }
784
- },
785
- render: (_args, value) => [{
786
- type: "text",
787
- text: value.sessions.length === 0
788
- ? "No matching sessions."
789
- : [
790
- value.sessions.map((entry) => [
791
- sessionReference(entry.title, entry.sessionId),
792
- entry.current === true ? "(this session)" : undefined,
793
- entry.subagent === true ? "(subagent)" : undefined,
794
- entry.state === "running" ? "(working now)" : undefined,
795
- entry.state === "archived" ? "(put away)" : undefined,
796
- entry.cwd,
797
- communicationStatusText(entry.communication)
798
- ].filter((part) => part !== undefined).join(" · ")).join("\n"),
799
- "通信状态仅为当前开关快照,不替代审批或其他发送限制;发送时仍重检。",
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,
801
- value.nextCursor ? `More matching sessions: use nextCursor ${value.nextCursor} before ${new Date(value.resultSetExpiresAt).toISOString()}.` : undefined,
802
- value.paginationUnavailable
803
- ].filter((part) => part !== undefined).join("\n")
804
- }]
805
- },
806
- execute: listSessions
807
- }));
808
- ctx.tools.register(defineTool({
809
- name: "session_wait",
810
- description: "Query a delivery receipt using sessionId and messageId from session_send or session_create. Wait for that message's recorded turn, never a later answer. Omitting messageId returns a session overview, not a message result. Read-only: never resumes, resends, changes, or interrupts the target.",
811
- parameters: {
812
- sessionId: {
813
- type: "string",
814
- required: true,
815
- description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
816
- },
817
- messageId: {
818
- type: "string",
819
- description: "The exact messageId returned with sessionId by session_send or session_create, including after timeout. Omit only for a session overview."
820
- },
821
- timeoutMs: {
822
- type: "number",
823
- 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."
824
- }
825
- },
826
- output: {
827
- schema: {
828
- type: "object",
829
- additionalProperties: false,
830
- properties: {
831
- sessionId: {
832
- type: "string",
833
- required: true
834
- },
835
- running: {
836
- type: "boolean",
837
- required: true
838
- },
839
- completed: {
840
- type: "boolean",
841
- required: true
842
- },
843
- waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
844
- elapsedMs: { type: "number" },
845
- scope: { type: "string", enum: ["message", "sessionOverview"] },
846
- ...receiptProperties
847
- }
848
- },
849
- presentationMeta: (_args, value) => ({ ...receiptMeta(value), scope: value.scope }),
850
- render: (_args, value) => [{
851
- type: "text",
852
- text: value.scope === "message" ? receiptText(value) :
853
- `Session overview for ${value.sessionId} (not a message result): ` +
854
- (waitNotice(value) ?? (value.running ? "running" : "idle")) +
855
- (value.output === undefined ? "" : `\nLatest session answer, not attributed to any receipt:\n${value.output}`)
856
- }]
857
- },
858
- async execute(args, exec) {
859
- const requested = args.sessionId.trim();
860
- if (requested === "") throw new Error("session_wait needs a session id");
861
- 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");
862
- const target = ctx.agents.get(requested);
863
- if (args.messageId !== undefined) {
864
- const messageId = args.messageId.trim();
865
- if (messageId === "") throw new Error("session_wait needs a non-empty messageId, or omit it for a session overview");
866
- const result = await observeReceipt(ctx, requested, messageId, args.timeoutMs, exec.signal);
867
- return {
868
- sessionId: requested, messageId, scope: "message", running: ctx.agents.get(requested)?.status === "running",
869
- ...result
870
- };
871
- }
872
-
873
- const result = await observeWait(args.timeoutMs, exec.signal, async (signal, onCleanup) => {
874
- if (target === undefined) {
875
- const query = ctx.get("sessionQuery");
876
- if (query === undefined) throw new Error(`session_wait cannot check ${JSON.stringify(requested)}: this DSH does not offer session lookup`);
877
- const known = (await query.listSessions(signal)).some(entry => String(entry.header.id) === requested);
878
- signal.throwIfAborted();
879
- if (!known) throw new Error(`session_wait cannot find session ${JSON.stringify(requested)}: no open or saved session has that id`);
880
- } else await target.whenIdle();
881
- signal.throwIfAborted();
882
- const answer = await readFinalAnswer(ctx, requested, signal, onCleanup);
883
- return answer === undefined ? {} : { output: answer };
884
- });
885
- return {
886
- sessionId: requested,
887
- scope: "sessionOverview",
888
- running: target?.status === "running",
889
- ...result
890
- };
891
- }
892
- }));
893
- }
894
- export { Config, apply, inject, name };
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { isAbsolute } from "node:path";
4
+ import z from "@deepseek-ai/schemastery";
5
+ import { defineTool } from "@deepseek-ai/dsh-tools";
6
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
+ import { brandString } from "@deepseek-ai/dsh-brand";
8
+ import { symbols } from "@deepseek-ai/cordis";
9
+ import { fallbackSessionTitle } from "@deepseek-ai/dsh-session-title";
10
+ import { createReceiptProjectionReader, foldReceipts, messageReceipt } from "./message-receipts.js";
11
+ import { createActivitySorter, readSlots } from "./session-activity.js";
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";
15
+
16
+ /** Stable Loader identity and producer-owned message source (V3 and V4). */
17
+ const name = "tool-session";
18
+ const Config = z.object({
19
+ defaultSend: z.boolean().default(true).volatile(),
20
+ defaultReceive: z.boolean().default(true).volatile(),
21
+ });
22
+ // Public fallback helper, using the shipped dsh-base 0.1.5-rc.2 limits.
23
+ // SessionTitleService.rename still enforces the host's accepted-title limit.
24
+ const fallbackTitleWords = 5;
25
+ const fallbackTitleBytes = 40;
26
+ /** Host services this tool needs: where it registers tools, and what it creates a session with. */
27
+ const inject = [
28
+ "tools",
29
+ "agents",
30
+ "sessionTitle",
31
+ "workspaceRegistry",
32
+ "agentDefaultModel",
33
+ "storageDomain"
34
+ ];
35
+ /** List the existing workspaces, so a rejected path tells the caller what to use instead. */
36
+ function workspaceCatalogue(registry) {
37
+ const items = registry.list();
38
+ return items.map((workspace) => `${workspace.title} (${workspace.path})`).join("; ");
39
+ }
40
+ /**
41
+ * Name a session in tool output, the way a person would say it: the title they
42
+ * will see in the sidebar, plus the id when the title is not known yet.
43
+ *
44
+ * Deliberately NOT the `@[label](dsh-session:…)` mention form. That form renders
45
+ * as a chip in message text but carries no navigation — it is a label, not a
46
+ * link — and whether it renders at all depends on machinery a tool result does
47
+ * not have. A receipt should read the same everywhere.
48
+ * @param title - the session's title, when it is known yet.
49
+ * @param sessionId - the session's id.
50
+ * @returns one line naming the session.
51
+ */
52
+ function sessionReference(title, sessionId) {
53
+ // Title reads hand back a snapshot, not a string; take the text either way so
54
+ // a receipt can never print an object.
55
+ const raw = typeof title === "object" && title !== null ? title.title : title;
56
+ const label = typeof raw === "string" ? raw.trim() : "";
57
+ return label === "" ? sessionId : `${label} · ${sessionId}`;
58
+ }
59
+ /**
60
+ * Ask before touching another session, except for the explicit full-access
61
+ * preset. Sandbox and approval are independent policies: `never` alone denies
62
+ * approval requests, it does not grant permission.
63
+ * @param ctx - services of the calling agent.
64
+ * @param exec - the running tool execution, including its cancellation signal.
65
+ * @param reason - what is about to happen, in the person's own terms.
66
+ * @throws when permission cannot be established or the request is not allowed.
67
+ */
68
+ async function requireApproval(ctx, exec, reason) {
69
+ const cancelled = () => {
70
+ if (exec.signal?.aborted) throw new Error(`the tool was cancelled, so ${reason} was not done`);
71
+ };
72
+ cancelled();
73
+ const approval = ctx.get("approval");
74
+ const sandboxPolicy = ctx.get("sandboxPolicy");
75
+ if (typeof approval?.overrideOf !== "function" || typeof approval?.request !== "function" || typeof sandboxPolicy?.resolve !== "function") {
76
+ throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
77
+ }
78
+ const session = exec.agent.session;
79
+ const mode = sandboxPolicy.resolve({ session })?.mode;
80
+ const policy = approval.overrideOf(session) ?? approval.config?.policy ?? "ask";
81
+ if (!["read-only", "workspace-write", "danger-full-access"].includes(mode) || !["ask", "never"].includes(policy)) {
82
+ throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
83
+ }
84
+ cancelled();
85
+ if (mode === "danger-full-access" && policy === "never") return;
86
+ const outcome = await approval.request({
87
+ agent: exec.agent,
88
+ toolName: exec.name,
89
+ callId: exec.callId,
90
+ reason,
91
+ signal: exec.signal
92
+ });
93
+ // A late answer must not revive a tool execution that has been cancelled.
94
+ cancelled();
95
+ if (outcome === "allowed-once") return;
96
+ throw new Error(
97
+ outcome === "rejected"
98
+ ? `the person declined: ${reason} was not done`
99
+ : `no answer to the approval request, so ${reason} was not done (${outcome})`
100
+ );
101
+ }
102
+ /**
103
+ * Give the new session the route selected for the caller's next step, falling
104
+ * back to the host default when no route is available.
105
+ */
106
+ function currentSelection(ctx, agent) {
107
+ let inherited;
108
+ try {
109
+ if (typeof agent.model?.current === "function") inherited = agent.model.current();
110
+ else {
111
+ const state = ctx.get("sessionProjections")?.stateOf(agent.session, "modelSelection");
112
+ inherited = state?.pending ?? state?.lastUsed;
113
+ }
114
+ } catch {}
115
+ if (inherited != null) return {
116
+ provider: inherited.provider,
117
+ model: inherited.model,
118
+ ...inherited.reasoningEffort === void 0 ? {} : { reasoningEffort: inherited.reasoningEffort }
119
+ };
120
+ const selected = ctx.agentDefaultModel.currentSelection();
121
+ return {
122
+ provider: selected.provider,
123
+ model: selected.model
124
+ };
125
+ }
126
+ /**
127
+ * Find the agent preset the new session should start on: the one this session
128
+ * uses, or the default preset when this session has none. A new session without
129
+ * a preset gets no tools, so it would sit in the list unable to do anything.
130
+ * @param ctx - services of the calling agent.
131
+ * @param agent - the calling agent.
132
+ * @param presets - the preset registry, when one is composed.
133
+ * @returns the preset id to use, or undefined when there is none.
134
+ */
135
+ async function resolvePreset(ctx, agent, presets) {
136
+ if (presets === void 0) return void 0;
137
+ try {
138
+ const current = typeof presets.presetForSession === "function"
139
+ ? presets.presetForSession(agent.session)
140
+ : ctx.get("sessionProjections")?.stateOf(agent.session, "agentPreset");
141
+ if (typeof current === "string") return current;
142
+ } catch {}
143
+ try {
144
+ return (await presets.resolve(void 0)).id;
145
+ } catch {
146
+ return void 0;
147
+ }
148
+ }
149
+ /**
150
+ * Bound a wait request to a usable budget: a missing or nonsensical value falls
151
+ * back to the default, and the ceiling keeps one tool call from hanging a turn
152
+ * forever. A timeout is reported, never treated as an error.
153
+ * @param requested - the caller's requested budget in milliseconds, if any.
154
+ * @returns the budget actually used.
155
+ */
156
+ function waitBudgetMs(requested) {
157
+ const DEFAULT_MS = 60_000;
158
+ const MAX_MS = 300_000;
159
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return DEFAULT_MS;
160
+ return Math.max(1, Math.min(Math.trunc(requested), MAX_MS));
161
+ }
162
+ /** Own only this observation: never forward its abort signal to a target agent. */
163
+ async function observeWait(requested, callerSignal, observe) {
164
+ const startedAt = Date.now();
165
+ const controller = new AbortController();
166
+ const cleanups = new Set();
167
+ const stopped = Promise.withResolvers();
168
+ let status;
169
+ const stop = (reason) => {
170
+ if (status !== undefined) return;
171
+ status = reason;
172
+ stopped.resolve({ waitStatus: reason, completed: false });
173
+ controller.abort();
174
+ };
175
+ const onAbort = () => stop("callerCancelled");
176
+ let timer;
177
+ try {
178
+ callerSignal?.addEventListener("abort", onAbort, { once: true });
179
+ if (callerSignal?.aborted) onAbort();
180
+ else timer = setTimeout(() => stop("timedOut"), waitBudgetMs(requested));
181
+ const result = await Promise.race([
182
+ stopped.promise,
183
+ (async () => {
184
+ controller.signal.throwIfAborted();
185
+ const value = await observe(controller.signal, (cleanup) => cleanups.add(cleanup));
186
+ controller.signal.throwIfAborted();
187
+ return { waitStatus: "completed", completed: true, ...value };
188
+ })()
189
+ ]);
190
+ return { ...result, elapsedMs: Date.now() - startedAt };
191
+ } finally {
192
+ clearTimeout(timer);
193
+ callerSignal?.removeEventListener("abort", onAbort);
194
+ // This also releases an outstanding polling timer or cancellable log read.
195
+ controller.abort();
196
+ await Promise.all([...cleanups].map(cleanup => cleanup()));
197
+ }
198
+ }
199
+
200
+ /** Snapshot the delivery itself, including reentrant claims/removals in followup. */
201
+ function deliveredReceipt(agent, messageId) {
202
+ try {
203
+ const events = agent.session.snapshotEvents?.();
204
+ if (events !== undefined) {
205
+ const result = messageReceipt(foldReceipts(events, agent.session.inheritedEventCount), messageId, events);
206
+ if (result.messageStatus !== "unknown") return result;
207
+ }
208
+ if ([agent.inbox?.nextTurn, agent.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) return { messageStatus: "queued", completed: false };
209
+ } catch {}
210
+ return { messageStatus: "unknown", completed: false, attributionNote: "Delivery returned, but this host does not provide reliable message attribution." };
211
+ }
212
+
213
+ /** Read one exact message receipt. Quiet or a missing queue entry proves nothing. */
214
+ async function waitForReceipt(ctx, readProjection, sessionId, messageId, signal, onCleanup, onProgress) {
215
+ for (;;) {
216
+ signal.throwIfAborted();
217
+ const log = await readSessionLog(ctx, sessionId, signal, onCleanup);
218
+ const target = ctx.agents.get(sessionId);
219
+ const cached = log.session !== undefined && target?.session === log.session ? readProjection(log.session) : undefined;
220
+ const state = cached !== undefined && cached.seq === (log.events.at(-1)?.seq ?? -1) ? cached : foldReceipts(log.events, log.inheritedEventCount);
221
+ let value = messageReceipt(state, messageId, log.events);
222
+ // Pending live input is positive queue evidence even on a host without
223
+ // durable inbox events. Its later disappearance will NEVER imply success.
224
+ if (value.messageStatus === "unknown" && [target?.inbox?.nextTurn, target?.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) {
225
+ value = { messageStatus: "queued", completed: false };
226
+ }
227
+ if (target === undefined && ["queued", "delivered"].includes(value.messageStatus)) value = { ...value, attributionNote: "The saved message has no recorded turn result. This read does not resume the target." };
228
+ onProgress(value);
229
+ if (!["queued", "delivered"].includes(value.messageStatus) || target === undefined) return value;
230
+ await delay(25, undefined, { signal });
231
+ }
232
+ }
233
+
234
+ /** Preserve the last receipt state on timeout/caller cancellation, never its output. */
235
+ async function observeReceipt(ctx, readProjection, sessionId, messageId, requested, callerSignal) {
236
+ let latest = { messageStatus: "unknown", completed: false };
237
+ const result = await observeWait(requested, callerSignal, (signal, onCleanup) =>
238
+ waitForReceipt(ctx, readProjection, sessionId, messageId, signal, onCleanup, value => { latest = value; }));
239
+ if (result.waitStatus === "completed") return result;
240
+ const { output, ...receipt } = latest;
241
+ return { ...receipt, ...result };
242
+ }
243
+
244
+ const receiptProperties = {
245
+ messageId: { type: "string" },
246
+ messageStatus: { type: "string", enum: ["queued", "delivered", "turnCompleted", "discarded", "cancelled", "blocked", "failed", "interrupted", "incomplete", "unknown"] },
247
+ turn: { type: "number" },
248
+ turnEndKind: { type: "string" },
249
+ attributionNote: { type: "string" },
250
+ output: { type: "string" }
251
+ };
252
+
253
+ function receiptMeta(value) {
254
+ return Object.fromEntries(["sessionId", "messageId", "messageStatus", "waitStatus", "turn", "turnEndKind", "attributionNote"].filter(key => value[key] !== undefined).map(key => [key, value[key]]));
255
+ }
256
+ const statusLabels = {
257
+ queued: "已排队", delivered: "已交给目标", turnCompleted: "目标本轮结束(不等于任务成功)",
258
+ discarded: "取消", cancelled: "取消", interrupted: "中断", failed: "失败",
259
+ incomplete: "未完整结束", blocked: "未完整结束", unknown: "暂无法确认",
260
+ };
261
+ function receiptText(value) {
262
+ const receipt = `Receipt: sessionId=${value.sessionId}, messageId=${value.messageId}`;
263
+ const notice = waitNotice(value);
264
+ return `${statusLabels[value.messageStatus] ?? "暂无法确认"}\n${receipt}` +
265
+ (value.attributionNote ? `\n${value.attributionNote}` : "") + (notice ? `\n${notice}` : "") +
266
+ (value.output === undefined ? "" : `\n${value.output}`);
267
+ }
268
+
269
+ /** A stopped observation says nothing about the target task's final outcome. */
270
+ function waitNotice(value) {
271
+ if (value.waitStatus === "callerCancelled") return "Waiting cancelled by the caller; the target task was not cancelled.";
272
+ if (value.waitStatus === "timedOut") return "Wait timed out; the target task was not cancelled. " + (value.messageId === undefined ? "Query this session overview again later." : "Query again with the same sessionId and messageId receipt; do not resend.");
273
+ return undefined;
274
+ }
275
+
276
+ /** Read a live snapshot or a cancellable, read-only persistence handle. */
277
+ async function readSessionLog(ctx, sessionId, signal, onCleanup = () => {}) {
278
+ signal?.throwIfAborted();
279
+ const live = ctx.agents.get(sessionId);
280
+ const own = typeof live?.session?.snapshotEvents === "function" ? live.session.snapshotEvents() : undefined;
281
+ let log = own === undefined ? undefined : { events: own, inheritedEventCount: live.session.inheritedEventCount ?? 0, session: live.session };
282
+ if (log === undefined) {
283
+ const persistence = ctx.get("sessionPersistence");
284
+ if (persistence !== undefined) {
285
+ // rc.2 query.readSession has no cancellation argument. Own a read-only
286
+ // persistence handle instead, never a resumed/writable target agent.
287
+ const reader = await persistence.open(sessionId, "read", { signal });
288
+ let closing;
289
+ const close = () => closing ??= Promise.resolve().then(() => reader.close());
290
+ onCleanup(close);
291
+ try {
292
+ signal?.throwIfAborted();
293
+ log = { ...await reader.read(undefined, undefined, { signal }), inheritedEventCount: reader.inheritedEventCount ?? 0 };
294
+ } finally {
295
+ await close();
296
+ }
297
+ } else {
298
+ const query = ctx.get("sessionQuery");
299
+ if (query === undefined) throw new Error(`this DSH cannot read session ${JSON.stringify(sessionId)}`);
300
+ // Compatibility with hosts exposing only the query service: the outer
301
+ // observation remains bounded, but that service owns its read lifetime.
302
+ log = await query.readSession(sessionId);
303
+ }
304
+ signal?.throwIfAborted();
305
+ }
306
+ return log;
307
+ }
308
+
309
+ /** Session-only overview, explicitly not a message result. */
310
+ async function readFinalAnswer(ctx, sessionId, signal, onCleanup) {
311
+ const { events } = await readSessionLog(ctx, sessionId, signal, onCleanup);
312
+ const texts = (content) => (content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("");
313
+ let answer;
314
+ const accumulated = [];
315
+ for (const event of events) {
316
+ if (event.type !== "assistant/message") continue;
317
+ const text = texts(event.data.message?.content);
318
+ if (text.trim() !== "") answer = text;
319
+ else accumulated.push(text);
320
+ }
321
+ const found = answer ?? (accumulated.length === 0 ? undefined : accumulated.join(""));
322
+ return found === undefined || found.trim() === "" ? undefined : found;
323
+ }
324
+ /**
325
+ * Report what a session is doing right now: working, waiting, or put away. The
326
+ * archive set lives on the workspace registry and answers whether the person has
327
+ * hidden the session from the sidebar, so it needs no log read of its own.
328
+ * @param ctx - services of the calling agent.
329
+ * @param sessionId - the session to describe.
330
+ * @returns `"running"`, `"archived"`, or `"idle"`.
331
+ */
332
+ function sessionState(ctx, sessionId) {
333
+ if (ctx.get("workspaceRegistry")?.archivedSessionIds?.some((id) => String(id) === sessionId) === true) return "archived";
334
+ return ctx.agents.get(sessionId)?.status === "running" ? "running" : "idle";
335
+ }
336
+ /** Pending resumes are shared by plugin instances using the same agent service. */
337
+ const targetResumes = new WeakMap();
338
+
339
+ function checkSendTarget(sessionId, header, callerAgent) {
340
+ if (sessionId === String(callerAgent.id) || sessionId === String(callerAgent.session?.header.id)) throw new Error("session_send cannot send to its own session: use the current conversation instead");
341
+ if ((header.delegationDepth ?? 0) > 0) throw new Error(`session_send cannot send to ${JSON.stringify(sessionId)}: that is a subagent session, not a regular one. Use send_message for it.`);
342
+ if (typeof header.cwd !== "string" || header.cwd.trim() === "") throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: this saved session does not record a working directory, and reopening it needs one. Send to a session that has a directory, or ask the person to open that session once.`);
343
+ }
344
+
345
+ /** Read target metadata without opening a writable session or publishing an agent. */
346
+ async function inspectSendTarget(ctx, sessionId, exec) {
347
+ exec.signal?.throwIfAborted();
348
+ if (sessionId === String(exec.agent.id) || sessionId === String(exec.agent.session?.header.id)) throw new Error("session_send cannot send to its own session: use the current conversation instead");
349
+ const live = ctx.agents.get(sessionId);
350
+ if (live !== void 0) {
351
+ checkSendTarget(sessionId, live.session.header, exec.agent);
352
+ return { agent: live, header: live.session.header };
353
+ }
354
+ const query = ctx.get("sessionQuery");
355
+ if (query === void 0) throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: this DSH does not offer session lookup`);
356
+ let record;
357
+ try {
358
+ // listSessions owns and releases its read resources; no handle escapes.
359
+ record = (await query.listSessions(exec.signal)).find((entry) => String(entry.header.id) === sessionId);
360
+ } catch (error) {
361
+ throw new Error(`session_send cannot read ${JSON.stringify(sessionId)}: ${error instanceof Error ? error.message : String(error)}`);
362
+ }
363
+ exec.signal?.throwIfAborted();
364
+ if (record === void 0) throw new Error(`session_send cannot find session ${JSON.stringify(sessionId)}: no open or saved session has that id`);
365
+ checkSendTarget(sessionId, record.header, exec.agent);
366
+ return { header: record.header };
367
+ }
368
+
369
+ /** Recheck after approval, then serialize resumes so concurrent sends share one agent. */
370
+ async function resolveTargetAgent(ctx, sessionId, exec) {
371
+ const agents = ctx.agents;
372
+ // Cordis creates a fresh traced proxy on each service read. Its exported
373
+ // original symbol gives stable identity; keep using the traced service for
374
+ // method calls so ownership and caller context are still preserved.
375
+ const serviceIdentity = agents[symbols.original] ?? agents;
376
+ let pending = targetResumes.get(serviceIdentity);
377
+ if (pending === void 0) targetResumes.set(serviceIdentity, pending = new Map());
378
+ const previous = pending.get(sessionId);
379
+ const operation = (async () => {
380
+ // A failed/cancelled earlier sender must not invalidate this sender's grant.
381
+ if (previous !== void 0) await previous.catch(() => {});
382
+ const inspected = await inspectSendTarget(ctx, sessionId, exec);
383
+ exec.signal?.throwIfAborted();
384
+ // Another host caller may have published the agent during the metadata read.
385
+ const live = agents.get(sessionId);
386
+ if (live !== void 0) {
387
+ checkSendTarget(sessionId, live.session.header, exec.agent);
388
+ return live;
389
+ }
390
+ const agentPresets = ctx.get("agentPresets");
391
+ const presetId = inspected.header.agentPreset;
392
+ const setup = agentPresets === void 0 || presetId === void 0 ? void 0 : async (agentCtx) => {
393
+ await agentPresets.mount(agentCtx, presetId);
394
+ };
395
+ const resumed = await agents.resume({
396
+ resumeSessionId: sessionId,
397
+ agentOptions: currentSelection(ctx, exec.agent),
398
+ signal: exec.signal,
399
+ ...setup === void 0 ? {} : { setup }
400
+ });
401
+ return resumed.agent;
402
+ })();
403
+ pending.set(sessionId, operation);
404
+ const release = () => {
405
+ if (pending.get(sessionId) === operation) pending.delete(sessionId);
406
+ };
407
+ // Keep the queue slot until the actual operation settles, even if this
408
+ // caller stops waiting. Otherwise a later sender could bypass an active resume.
409
+ void operation.then(release, release);
410
+ if (previous !== void 0 && exec.signal !== void 0) {
411
+ const cancelled = Promise.withResolvers();
412
+ const onAbort = () => cancelled.reject(exec.signal.reason);
413
+ try {
414
+ exec.signal.addEventListener("abort", onAbort, { once: true });
415
+ if (exec.signal.aborted) onAbort();
416
+ await Promise.race([previous.catch(() => {}), cancelled.promise]);
417
+ } finally {
418
+ exec.signal.removeEventListener("abort", onAbort);
419
+ }
420
+ }
421
+ return await operation;
422
+ }
423
+ /**
424
+ * Register `session_create` and `session_send`.
425
+ * @param ctx - services of the agent this plugin was loaded for.
426
+ */
427
+ function apply(ctx, config = Config({})) {
428
+ const readReceiptProjection = createReceiptProjectionReader(ctx);
429
+ const permissions = communicationPermissions(ctx, () => ({
430
+ send: config.defaultSend.get(),
431
+ receive: config.defaultReceive.get(),
432
+ }));
433
+ ctx.inject(["typert", "connection"], scope => { scope.plugin(CommunicationRemote, permissions); });
434
+ ctx.inject(["settings"], scope => {
435
+ scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber));
436
+ });
437
+ const inSlot = readSlots();
438
+ const sortByActivity = createActivitySorter(ctx, inSlot);
439
+ const listSessions = createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState, permissions);
440
+ ctx.tools.register(defineTool({
441
+ name: "session_communication_status",
442
+ 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.",
443
+ parameters: { sessionId: { type: "string", required: true, description: "Target ordinary session ID." } },
444
+ output: {
445
+ schema: { type: "object", additionalProperties: false, properties: {
446
+ sessionId: { type: "string", required: true },
447
+ communication: { ...communicationStatusSchema, required: true },
448
+ } },
449
+ render: (_args, value) => [{ type: "text", text: `${communicationStatusText(value.communication)}。仅为当前开关状态,不代表已投递,也不替代审批和其他发送限制;发送时仍会重检。` }],
450
+ },
451
+ async execute(args, exec) {
452
+ const requested = args.sessionId.trim();
453
+ let communication = unknownCommunication();
454
+ try {
455
+ const sourceId = trustedSource(exec);
456
+ if (!requested || requested.length > 1024) return { sessionId: requested, communication };
457
+ // Resolve visibility before reading permissions: arbitrary IDs must
458
+ // never reveal defaults or records outside the host's catalog.
459
+ const query = ctx.get("sessionQuery");
460
+ if (!query) return { sessionId: requested, communication };
461
+ const record = (await query.listSessions(exec.signal)).find(row =>
462
+ String(row.header.id) === requested && (row.header.delegationDepth ?? 0) <= 0 && row.header.origin !== "subagent");
463
+ exec.signal?.throwIfAborted();
464
+ if (!record) return { sessionId: requested, communication };
465
+ // Read switch state only. cwd/self and other delivery restrictions
466
+ // remain session_send concerns, just as for list_sessions rows.
467
+ [communication] = await permissions.statuses(sourceId, [requested]);
468
+ } catch {
469
+ exec.signal?.throwIfAborted();
470
+ }
471
+ return { sessionId: requested, communication };
472
+ },
473
+ }));
474
+ ctx.tools.register(defineTool({
475
+ name: "session_create",
476
+ description: "Start a new chat session the person can see in the session list. The new session runs its own first turn and keeps going on its own; this call returns as soon as it exists. Pass workspacePath to put it under that workspace, or leave it out to leave it ungrouped. Use this when the work deserves its own session the person can open and continue; use a subagent instead when the work should stay inside this conversation.",
477
+ parameters: {
478
+ prompt: {
479
+ type: "string",
480
+ required: true,
481
+ description: "The new session's first task, delivered with plugin provenance. Write it self-contained: the new session cannot see this conversation."
482
+ },
483
+ workspacePath: {
484
+ type: "string",
485
+ description: "Full path of a workspace that already exists (for example \"E:\\\\Users\\\\Ryuu\\\\Desktop\"). Leave it out to leave the new session ungrouped. This tool never creates a workspace, so an unknown path fails with the list of existing ones."
486
+ },
487
+ title: {
488
+ type: "string",
489
+ description: "Optional fixed title. If omitted or blank, derive it once from the prompt using the host's public normalization and truncation rules (first 5 whitespace-delimited words, at most 40 UTF-8 bytes). No extra model call; later messages do not automatically rename it. The person can still rename it manually."
490
+ },
491
+ wait: {
492
+ type: "boolean",
493
+ description: "Wait for the first message's recorded turn to end before returning. Defaults to false; bounded by timeoutMs."
494
+ },
495
+ timeoutMs: {
496
+ type: "number",
497
+ description: "Wait budget in milliseconds. Defaults to 60000, at most 300000. Timeout or caller cancellation only ends this wait."
498
+ }
499
+ },
500
+ output: {
501
+ schema: {
502
+ type: "object",
503
+ additionalProperties: false,
504
+ properties: {
505
+ sessionId: {
506
+ type: "string",
507
+ required: true
508
+ },
509
+ grouped: {
510
+ type: "boolean",
511
+ required: true
512
+ },
513
+ cwd: {
514
+ type: "string",
515
+ required: true
516
+ },
517
+ workspaceId: { type: "string" },
518
+ workspacePath: { type: "string" },
519
+ title: { type: "string" },
520
+ waited: { type: "boolean" },
521
+ completed: { type: "boolean" },
522
+ waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
523
+ elapsedMs: { type: "number" },
524
+ ...receiptProperties
525
+ }
526
+ },
527
+ // rc.2 persists this projection on tool/result and exposes it as
528
+ // ToolResultNode.meta. The canonical value alone does not survive replay.
529
+ presentationMeta: (_args, value) => ({
530
+ sessionId: value.sessionId,
531
+ ...receiptMeta(value),
532
+ ...typeof value.title === "string" ? { title: value.title } : {}
533
+ }),
534
+ // Keep the receipt readable for clients without the session card.
535
+ render: (_args, value) => [{
536
+ type: "text",
537
+ text: (value.grouped === true
538
+ ? `Created session: ${sessionReference(value.title, value.sessionId)} in workspace ${value.workspacePath}`
539
+ : `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`) + `\n${receiptText(value)}`
540
+ }]
541
+ },
542
+ async execute(args, exec) {
543
+ if (exec.agent === void 0) throw new Error("session_create must run inside a session");
544
+ const sourceId = trustedSource(exec);
545
+ const sessionId = brandString(`session-${randomUUID()}`);
546
+ await permissions.check(sourceId, sessionId);
547
+ const prompt = args.prompt.trim();
548
+ if (prompt === "") throw new Error("session_create needs a prompt: it becomes the new session's first user message");
549
+ let workspace;
550
+ let cwd;
551
+ if (args.workspacePath !== void 0) {
552
+ const requested = args.workspacePath.trim();
553
+ if (!isAbsolute(requested)) throw new Error(`session_create needs a full workspace path, got ${JSON.stringify(args.workspacePath)}`);
554
+ workspace = await ctx.workspaceRegistry.resolveByPath(requested);
555
+ if (workspace === void 0) {
556
+ throw new Error(`session_create cannot use ${JSON.stringify(requested)}: no workspace has that path, and this tool does not create workspaces. Existing workspaces: ${workspaceCatalogue(ctx.workspaceRegistry)}. Use one of those paths, or leave workspacePath out to create the session under Ungrouped.`);
557
+ }
558
+ cwd = workspace.path;
559
+ } else {
560
+ cwd = exec.agent.session.header.cwd;
561
+ if (cwd === void 0) throw new Error("session_create needs a working directory, and this session has none");
562
+ }
563
+ // Ask before creating anything: a session that appears in the person's
564
+ // list without them knowing about it is the whole risk of this tool.
565
+ const where = workspace === void 0 ? "ungrouped" : `in workspace ${JSON.stringify(workspace.path)}`;
566
+ await permissions.check(sourceId, sessionId);
567
+ await requireApproval(ctx, exec, `create a new session ${where}, starting with: ${prompt.slice(0, 120)}`);
568
+ await permissions.check(sourceId, sessionId);
569
+ const agentOptions = currentSelection(ctx, exec.agent);
570
+ const agentPresets = ctx.get("agentPresets");
571
+ const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
572
+ const publication = await permissions.prepareCreation(sourceId, sessionId, exec);
573
+ exec.signal?.throwIfAborted();
574
+ let handle;
575
+ let attached = false;
576
+ let sent;
577
+ try {
578
+ handle = await ctx.agents.create({
579
+ signal: exec.signal,
580
+ sessionId,
581
+ agentOptions,
582
+ meta: {
583
+ cwd,
584
+ parentSession: String(exec.agent.session.header.id),
585
+ ...presetId === void 0 ? {} : { agentPreset: presetId }
586
+ },
587
+ setup: async (agentCtx) => {
588
+ if (agentPresets !== void 0 && presetId !== void 0) await agentPresets.mount(agentCtx, presetId);
589
+ return publication;
590
+ }
591
+ });
592
+ exec.signal?.throwIfAborted();
593
+ if (workspace !== void 0) {
594
+ await workspace.attachSession(sessionId);
595
+ attached = true;
596
+ }
597
+ exec.signal?.throwIfAborted();
598
+ const title = args.title?.trim() || fallbackSessionTitle(prompt, fallbackTitleWords, fallbackTitleBytes);
599
+ sent = createUserMessage({
600
+ content: [{
601
+ type: "text",
602
+ text: prompt
603
+ }],
604
+ source: {
605
+ kind: name,
606
+ form: "relay"
607
+ }
608
+ });
609
+ await permissions.admit(sourceId, sessionId, exec, () => {
610
+ // Renaming writes to the log. Keep it inside admission so a denial
611
+ // during asynchronous creation cannot leave a title-only child.
612
+ ctx.sessionTitle.rename(handle.agent.session, title);
613
+ exec.signal?.throwIfAborted();
614
+ return handle.agent.followup(sent);
615
+ });
616
+ } catch (error) {
617
+ if (attached) try {
618
+ await workspace.detachSession(sessionId);
619
+ } catch {}
620
+ if (handle !== void 0) try {
621
+ await handle.dispose();
622
+ } catch {}
623
+ throw error;
624
+ }
625
+ // Once delivered, the target owns its lifetime. Ending this observation
626
+ // must not detach its workspace or dispose its handle.
627
+ const waited = args.wait === true ? await observeReceipt(ctx, readReceiptProjection, String(sessionId), sent.id, args.timeoutMs, exec.signal) : undefined;
628
+ // Read the accepted title after host normalization (or a manual rename).
629
+ let currentTitle;
630
+ try {
631
+ // The service returns a title snapshot; the text lives on `.title`.
632
+ currentTitle = ctx.sessionTitle.get(handle.agent.session)?.title;
633
+ } catch {}
634
+ return {
635
+ sessionId: String(sessionId),
636
+ messageId: sent.id,
637
+ ...waited === undefined ? deliveredReceipt(handle.agent, sent.id) : { waited: true, ...waited },
638
+ grouped: workspace !== void 0,
639
+ cwd,
640
+ ...currentTitle === void 0 || currentTitle === "" ? {} : { title: String(currentTitle) },
641
+ ...workspace === void 0 ? {} : {
642
+ workspaceId: String(workspace.id),
643
+ workspacePath: workspace.path
644
+ }
645
+ };
646
+ }
647
+ }));
648
+ ctx.tools.register(defineTool({
649
+ name: "session_send",
650
+ description: "Send a message to an existing chat session so that session continues on its own — including one this session started earlier. It cannot send to itself, cannot send to a subagent the agent spawned (use send_message for those), and never rewrites past messages. Sending returns right away; the target handles the message when it can.",
651
+ parameters: {
652
+ sessionId: {
653
+ type: "string",
654
+ required: true,
655
+ description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
656
+ },
657
+ message: {
658
+ type: "string",
659
+ required: true,
660
+ description: "Message text. Write it self-contained: the target cannot see this conversation unless the person linked the two."
661
+ },
662
+ wait: {
663
+ type: "boolean",
664
+ 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."
665
+ },
666
+ timeoutMs: {
667
+ type: "number",
668
+ description: "How long to observe this receipt when wait is true, in milliseconds. Defaults to 60000, at most 300000. Timeout never proves success or failure and never resends or cancels the target."
669
+ }
670
+ },
671
+ output: {
672
+ schema: {
673
+ type: "object",
674
+ additionalProperties: false,
675
+ properties: {
676
+ sessionId: {
677
+ type: "string",
678
+ required: true
679
+ },
680
+ cwd: {
681
+ type: "string",
682
+ required: true
683
+ },
684
+ waited: { type: "boolean" },
685
+ completed: { type: "boolean" },
686
+ waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
687
+ elapsedMs: { type: "number" },
688
+ ...receiptProperties
689
+ }
690
+ },
691
+ presentationMeta: (_args, value) => receiptMeta(value),
692
+ render: (_args, value) => [{
693
+ type: "text",
694
+ text: receiptText(value)
695
+ }]
696
+ },
697
+ async execute(args, exec) {
698
+ if (exec.agent === void 0) throw new Error("session_send must run inside a session");
699
+ const sourceId = trustedSource(exec);
700
+ const requested = args.sessionId.trim();
701
+ if (requested === "") throw new Error("session_send needs a session id");
702
+ const message = args.message.trim();
703
+ if (message === "") throw new Error("session_send needs a message");
704
+ await permissions.check(sourceId, requested);
705
+ await inspectSendTarget(ctx, requested, exec);
706
+ await permissions.check(sourceId, requested);
707
+ await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(requested)}: ${message.slice(0, 120)}`);
708
+ await permissions.check(sourceId, requested);
709
+ const target = await resolveTargetAgent(ctx, requested, exec);
710
+ exec.signal?.throwIfAborted();
711
+ const targetId = String(target.id);
712
+ if (targetId !== requested) throw new Error("session_send resolved a different target; no message was sent");
713
+ checkSendTarget(targetId, target.session.header, exec.agent);
714
+ const sent = createUserMessage({
715
+ content: [{
716
+ type: "text",
717
+ text: message
718
+ }],
719
+ source: {
720
+ kind: name,
721
+ form: "relay"
722
+ }
723
+ });
724
+ await permissions.admit(sourceId, targetId, exec, () => target.followup(sent));
725
+ if (args.wait !== true) return {
726
+ sessionId: targetId,
727
+ messageId: sent.id,
728
+ ...deliveredReceipt(target, sent.id),
729
+ cwd: String(target.session.header.cwd ?? "")
730
+ };
731
+ const result = await observeReceipt(ctx, readReceiptProjection, targetId, sent.id, args.timeoutMs, exec.signal);
732
+ return {
733
+ sessionId: targetId,
734
+ messageId: sent.id,
735
+ cwd: String(target.session.header.cwd ?? ""),
736
+ waited: true,
737
+ ...result
738
+ };
739
+ }
740
+ }));
741
+ ctx.tools.register(defineTool({
742
+ name: "list_sessions",
743
+ 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.",
744
+ parameters: {
745
+ 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." },
746
+ workspaceId: { type: "string", description: "Existing workspace ID (at most 256 UTF-8 bytes); mutually exclusive with workspacePath. Uses actual workspace membership." },
747
+ workspacePath: { type: "string", description: "Absolute path of an existing registered workspace (at most 4096 UTF-8 bytes); mutually exclusive with workspaceId." },
748
+ cursor: { type: "string", description: "Opaque nextCursor from this caller's previous page. Omit filters to inherit them; explicit filters must match. Expires after 5 minutes; no cursor starts a fresh query." },
749
+ limit: {
750
+ type: "number",
751
+ description: "How many sessions to list, most recently active first. Defaults to 20, capped at 100. May change between pages."
752
+ }
753
+ },
754
+ output: {
755
+ schema: {
756
+ type: "object",
757
+ additionalProperties: false,
758
+ properties: {
759
+ sessions: {
760
+ type: "array",
761
+ required: true,
762
+ items: {
763
+ type: "object",
764
+ additionalProperties: false,
765
+ properties: {
766
+ sessionId: {
767
+ type: "string",
768
+ required: true
769
+ },
770
+ title: { type: "string" },
771
+ cwd: { type: "string" },
772
+ state: {
773
+ type: "string",
774
+ required: true,
775
+ enum: ["running", "idle", "archived"],
776
+ 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)."
777
+ },
778
+ current: { type: "boolean" },
779
+ subagent: { type: "boolean" },
780
+ communication: { ...communicationStatusSchema, required: true }
781
+ }
782
+ }
783
+ },
784
+ matchedTotal: { type: "number", required: true, description: "Ordinary sessions matching the initial successful scan, before limit; frozen across pages." },
785
+ nextCursor: { type: "string" },
786
+ resultSetCreatedAt: { type: "number", description: "Result set creation time in Unix milliseconds; not an atomic database snapshot." },
787
+ resultSetExpiresAt: { type: "number", description: "Fixed expiration time in Unix milliseconds." },
788
+ paginationUnavailable: { type: "string" },
789
+ workspaceId: { type: "string" },
790
+ workspacePath: { type: "string" },
791
+ total: {
792
+ type: "number",
793
+ required: true
794
+ }
795
+ }
796
+ },
797
+ render: (_args, value) => [{
798
+ type: "text",
799
+ text: value.sessions.length === 0
800
+ ? "No matching sessions."
801
+ : [
802
+ value.sessions.map((entry) => [
803
+ sessionReference(entry.title, entry.sessionId),
804
+ entry.current === true ? "(this session)" : undefined,
805
+ entry.subagent === true ? "(subagent)" : undefined,
806
+ entry.state === "running" ? "(working now)" : undefined,
807
+ entry.state === "archived" ? "(put away)" : undefined,
808
+ entry.cwd,
809
+ communicationStatusText(entry.communication)
810
+ ].filter((part) => part !== undefined).join(" · ")).join("\n"),
811
+ "通信状态仅为当前开关快照,不替代审批或其他发送限制;发送时仍重检。",
812
+ value.sessions.some((entry) => entry.state === "archived") ? "Sessions marked (put away) are archived: they are hidden from the sidebar but still listed here." : undefined,
813
+ value.nextCursor ? `More matching sessions: use nextCursor ${value.nextCursor} before ${new Date(value.resultSetExpiresAt).toISOString()}.` : undefined,
814
+ value.paginationUnavailable
815
+ ].filter((part) => part !== undefined).join("\n")
816
+ }]
817
+ },
818
+ execute: listSessions
819
+ }));
820
+ ctx.tools.register(defineTool({
821
+ name: "session_wait",
822
+ description: "Query a delivery receipt using sessionId and messageId from session_send or session_create. Wait for that message's recorded turn, never a later answer. Omitting messageId returns a session overview, not a message result. Read-only: never resumes, resends, changes, or interrupts the target.",
823
+ parameters: {
824
+ sessionId: {
825
+ type: "string",
826
+ required: true,
827
+ description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
828
+ },
829
+ messageId: {
830
+ type: "string",
831
+ description: "The exact messageId returned with sessionId by session_send or session_create, including after timeout. Omit only for a session overview."
832
+ },
833
+ timeoutMs: {
834
+ type: "number",
835
+ 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."
836
+ }
837
+ },
838
+ output: {
839
+ schema: {
840
+ type: "object",
841
+ additionalProperties: false,
842
+ properties: {
843
+ sessionId: {
844
+ type: "string",
845
+ required: true
846
+ },
847
+ running: {
848
+ type: "boolean",
849
+ required: true
850
+ },
851
+ completed: {
852
+ type: "boolean",
853
+ required: true
854
+ },
855
+ waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
856
+ elapsedMs: { type: "number" },
857
+ scope: { type: "string", enum: ["message", "sessionOverview"] },
858
+ ...receiptProperties
859
+ }
860
+ },
861
+ presentationMeta: (_args, value) => ({ ...receiptMeta(value), scope: value.scope }),
862
+ render: (_args, value) => [{
863
+ type: "text",
864
+ text: value.scope === "message" ? receiptText(value) :
865
+ `Session overview for ${value.sessionId} (not a message result): ` +
866
+ (waitNotice(value) ?? (value.running ? "running" : "idle")) +
867
+ (value.output === undefined ? "" : `\nLatest session answer, not attributed to any receipt:\n${value.output}`)
868
+ }]
869
+ },
870
+ async execute(args, exec) {
871
+ const requested = args.sessionId.trim();
872
+ if (requested === "") throw new Error("session_wait needs a session id");
873
+ 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");
874
+ const target = ctx.agents.get(requested);
875
+ if (args.messageId !== undefined) {
876
+ const messageId = args.messageId.trim();
877
+ if (messageId === "") throw new Error("session_wait needs a non-empty messageId, or omit it for a session overview");
878
+ const result = await observeReceipt(ctx, readReceiptProjection, requested, messageId, args.timeoutMs, exec.signal);
879
+ return {
880
+ sessionId: requested, messageId, scope: "message", running: ctx.agents.get(requested)?.status === "running",
881
+ ...result
882
+ };
883
+ }
884
+
885
+ const result = await observeWait(args.timeoutMs, exec.signal, async (signal, onCleanup) => {
886
+ if (target === undefined) {
887
+ const query = ctx.get("sessionQuery");
888
+ if (query === undefined) throw new Error(`session_wait cannot check ${JSON.stringify(requested)}: this DSH does not offer session lookup`);
889
+ const known = (await query.listSessions(signal)).some(entry => String(entry.header.id) === requested);
890
+ signal.throwIfAborted();
891
+ if (!known) throw new Error(`session_wait cannot find session ${JSON.stringify(requested)}: no open or saved session has that id`);
892
+ } else await target.whenIdle();
893
+ signal.throwIfAborted();
894
+ const answer = await readFinalAnswer(ctx, requested, signal, onCleanup);
895
+ return answer === undefined ? {} : { output: answer };
896
+ });
897
+ return {
898
+ sessionId: requested,
899
+ scope: "sessionOverview",
900
+ running: target?.status === "running",
901
+ ...result
902
+ };
903
+ }
904
+ }));
905
+ }
906
+ export { Config, apply, inject, name };