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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,14 +1,23 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { isAbsolute } from "node:path";
3
4
  import z from "@deepseek-ai/schemastery";
4
5
  import { defineTool } from "@deepseek-ai/dsh-tools";
5
6
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
6
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 } from "./session-activity.js";
7
12
 
8
13
  /** Stable Loader identity. */
9
14
  const name = "tool-session";
10
15
  /** Nothing to configure. */
11
16
  const Config = z.object({});
17
+ // Public fallback helper, using the shipped dsh-base 0.1.5-rc.2 limits.
18
+ // SessionTitleService.rename still enforces the host's accepted-title limit.
19
+ const fallbackTitleWords = 5;
20
+ const fallbackTitleBytes = 40;
12
21
  /** Host services this tool needs: where it registers tools, and what it creates a session with. */
13
22
  const inject = [
14
23
  "tools",
@@ -42,31 +51,41 @@ function sessionReference(title, sessionId) {
42
51
  return label === "" ? sessionId : `${label} · ${sessionId}`;
43
52
  }
44
53
  /**
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.
54
+ * Ask before touching another session, except for the explicit full-access
55
+ * preset. Sandbox and approval are independent policies: `never` alone denies
56
+ * approval requests, it does not grant permission.
49
57
  * @param ctx - services of the calling agent.
50
- * @param exec - the running tool execution, for the agent and call id.
58
+ * @param exec - the running tool execution, including its cancellation signal.
51
59
  * @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.
60
+ * @throws when permission cannot be established or the request is not allowed.
54
61
  */
55
62
  async function requireApproval(ctx, exec, reason) {
63
+ const cancelled = () => {
64
+ if (exec.signal?.aborted) throw new Error(`the tool was cancelled, so ${reason} was not done`);
65
+ };
66
+ cancelled();
56
67
  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`);
68
+ const sandboxPolicy = ctx.get("sandboxPolicy");
69
+ if (typeof approval?.overrideOf !== "function" || typeof approval?.request !== "function" || typeof sandboxPolicy?.resolve !== "function") {
70
+ throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
71
+ }
72
+ const session = exec.agent.session;
73
+ const mode = sandboxPolicy.resolve({ session })?.mode;
74
+ const policy = approval.overrideOf(session) ?? approval.config?.policy ?? "ask";
75
+ if (!["read-only", "workspace-write", "danger-full-access"].includes(mode) || !["ask", "never"].includes(policy)) {
76
+ throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
61
77
  }
62
- const policy = approval.effectivePolicy(exec.agent.session);
63
- if (policy !== "ask") return;
78
+ cancelled();
79
+ if (mode === "danger-full-access" && policy === "never") return;
64
80
  const outcome = await approval.request({
65
81
  agent: exec.agent,
66
82
  toolName: exec.name,
67
83
  callId: exec.callId,
68
- reason
84
+ reason,
85
+ signal: exec.signal
69
86
  });
87
+ // A late answer must not revive a tool execution that has been cancelled.
88
+ cancelled();
70
89
  if (outcome === "allowed-once") return;
71
90
  throw new Error(
72
91
  outcome === "rejected"
@@ -129,29 +148,151 @@ function waitBudgetMs(requested) {
129
148
  const DEFAULT_MS = 60_000;
130
149
  const MAX_MS = 300_000;
131
150
  if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return DEFAULT_MS;
132
- return Math.min(Math.trunc(requested), MAX_MS);
151
+ return Math.max(1, Math.min(Math.trunc(requested), MAX_MS));
133
152
  }
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) {
153
+ /** Own only this observation: never forward its abort signal to a target agent. */
154
+ async function observeWait(requested, callerSignal, observe) {
155
+ const startedAt = Date.now();
156
+ const controller = new AbortController();
157
+ const cleanups = new Set();
158
+ const stopped = Promise.withResolvers();
159
+ let status;
160
+ const stop = (reason) => {
161
+ if (status !== undefined) return;
162
+ status = reason;
163
+ stopped.resolve({ waitStatus: reason, completed: false });
164
+ controller.abort();
165
+ };
166
+ const onAbort = () => stop("callerCancelled");
167
+ let timer;
168
+ try {
169
+ callerSignal?.addEventListener("abort", onAbort, { once: true });
170
+ if (callerSignal?.aborted) onAbort();
171
+ else timer = setTimeout(() => stop("timedOut"), waitBudgetMs(requested));
172
+ const result = await Promise.race([
173
+ stopped.promise,
174
+ (async () => {
175
+ controller.signal.throwIfAborted();
176
+ const value = await observe(controller.signal, (cleanup) => cleanups.add(cleanup));
177
+ controller.signal.throwIfAborted();
178
+ return { waitStatus: "completed", completed: true, ...value };
179
+ })()
180
+ ]);
181
+ return { ...result, elapsedMs: Date.now() - startedAt };
182
+ } finally {
183
+ clearTimeout(timer);
184
+ callerSignal?.removeEventListener("abort", onAbort);
185
+ // This also releases an outstanding polling timer or cancellable log read.
186
+ controller.abort();
187
+ await Promise.all([...cleanups].map(cleanup => cleanup()));
188
+ }
189
+ }
190
+
191
+ /** Snapshot the delivery itself, including reentrant claims/removals in followup. */
192
+ function deliveredReceipt(agent, messageId) {
193
+ try {
194
+ const events = agent.session.snapshotEvents?.();
195
+ if (events !== undefined) {
196
+ const result = messageReceipt(foldReceipts(events, agent.session.inheritedEventCount), messageId, events);
197
+ if (result.messageStatus !== "unknown") return result;
198
+ }
199
+ if ([agent.inbox?.nextTurn, agent.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) return { messageStatus: "queued", completed: false };
200
+ } catch {}
201
+ return { messageStatus: "unknown", completed: false, attributionNote: "Delivery returned, but this host does not provide reliable message attribution." };
202
+ }
203
+
204
+ /** Read one exact message receipt. Quiet or a missing queue entry proves nothing. */
205
+ async function waitForReceipt(ctx, sessionId, messageId, signal, onCleanup, onProgress) {
206
+ for (;;) {
207
+ signal.throwIfAborted();
208
+ const log = await readSessionLog(ctx, sessionId, signal, onCleanup);
209
+ const target = ctx.agents.get(sessionId);
210
+ const cached = log.session !== undefined && target?.session === log.session ? ctx.get?.("sessionProjections")?.stateOf?.(log.session, receiptProjectionKey) : undefined;
211
+ const state = cached !== undefined && cached.seq === (log.events.at(-1)?.seq ?? -1) ? cached : foldReceipts(log.events, log.inheritedEventCount);
212
+ let value = messageReceipt(state, messageId, log.events);
213
+ // Pending live input is positive queue evidence even on a host without
214
+ // durable inbox events. Its later disappearance will NEVER imply success.
215
+ if (value.messageStatus === "unknown" && [target?.inbox?.nextTurn, target?.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) {
216
+ value = { messageStatus: "queued", completed: false };
217
+ }
218
+ 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." };
219
+ onProgress(value);
220
+ if (!["queued", "delivered"].includes(value.messageStatus) || target === undefined) return value;
221
+ await delay(25, undefined, { signal });
222
+ }
223
+ }
224
+
225
+ /** Preserve the last receipt state on timeout/caller cancellation, never its output. */
226
+ async function observeReceipt(ctx, sessionId, messageId, requested, callerSignal) {
227
+ let latest = { messageStatus: "unknown", completed: false };
228
+ const result = await observeWait(requested, callerSignal, (signal, onCleanup) =>
229
+ waitForReceipt(ctx, sessionId, messageId, signal, onCleanup, value => { latest = value; }));
230
+ if (result.waitStatus === "completed") return result;
231
+ const { output, ...receipt } = latest;
232
+ return { ...receipt, ...result };
233
+ }
234
+
235
+ const receiptProperties = {
236
+ messageId: { type: "string" },
237
+ messageStatus: { type: "string", enum: ["queued", "delivered", "turnCompleted", "discarded", "cancelled", "blocked", "failed", "interrupted", "incomplete", "unknown"] },
238
+ turn: { type: "number" },
239
+ turnEndKind: { type: "string" },
240
+ attributionNote: { type: "string" },
241
+ output: { type: "string" }
242
+ };
243
+
244
+ function receiptText(value) {
245
+ const receipt = `Receipt: sessionId=${value.sessionId}, messageId=${value.messageId}`;
246
+ const notice = waitNotice(value);
247
+ return `${receipt}\nMessage status: ${value.messageStatus ?? "queued"}${value.turn === undefined ? "" : `; turn ${value.turn}`}.` +
248
+ (value.messageStatus === "turnCompleted" ? " The recorded turn completed; this does not verify the business task succeeded." : "") +
249
+ (value.attributionNote ? `\n${value.attributionNote}` : "") + (notice ? `\n${notice}` : "") +
250
+ (value.output === undefined ? "" : `\n${value.output}`);
251
+ }
252
+
253
+ /** A stopped observation says nothing about the target task's final outcome. */
254
+ function waitNotice(value) {
255
+ if (value.waitStatus === "callerCancelled") return "Waiting cancelled by the caller; the target task was not cancelled.";
256
+ 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.");
257
+ return undefined;
258
+ }
259
+
260
+ /** Read a live snapshot or a cancellable, read-only persistence handle. */
261
+ async function readSessionLog(ctx, sessionId, signal, onCleanup = () => {}) {
262
+ signal?.throwIfAborted();
146
263
  const live = ctx.agents.get(sessionId);
147
264
  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;
265
+ let log = own === undefined ? undefined : { events: own, inheritedEventCount: live.session.inheritedEventCount ?? 0, session: live.session };
266
+ if (log === undefined) {
267
+ const persistence = ctx.get("sessionPersistence");
268
+ if (persistence !== undefined) {
269
+ // rc.2 query.readSession has no cancellation argument. Own a read-only
270
+ // persistence handle instead, never a resumed/writable target agent.
271
+ const reader = await persistence.open(sessionId, "read", { signal });
272
+ let closing;
273
+ const close = () => closing ??= Promise.resolve().then(() => reader.close());
274
+ onCleanup(close);
275
+ try {
276
+ signal?.throwIfAborted();
277
+ log = { ...await reader.read(undefined, undefined, { signal }), inheritedEventCount: reader.inheritedEventCount ?? 0 };
278
+ } finally {
279
+ await close();
280
+ }
281
+ } else {
282
+ const query = ctx.get("sessionQuery");
283
+ if (query === undefined) throw new Error(`this DSH cannot read session ${JSON.stringify(sessionId)}`);
284
+ // Compatibility with hosts exposing only the query service: the outer
285
+ // observation remains bounded, but that service owns its read lifetime.
286
+ log = await query.readSession(sessionId);
287
+ }
288
+ signal?.throwIfAborted();
154
289
  }
290
+ return log;
291
+ }
292
+
293
+ /** Session-only overview, explicitly not a message result. */
294
+ async function readFinalAnswer(ctx, sessionId, signal, onCleanup) {
295
+ const { events } = await readSessionLog(ctx, sessionId, signal, onCleanup);
155
296
  const texts = (content) => (content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("");
156
297
  let answer;
157
298
  const accumulated = [];
@@ -176,45 +317,103 @@ function sessionState(ctx, sessionId) {
176
317
  if (ctx.get("workspaceRegistry")?.archivedSessionIds?.some((id) => String(id) === sessionId) === true) return "archived";
177
318
  return ctx.agents.get(sessionId)?.status === "running" ? "running" : "idle";
178
319
  }
179
- /**
180
- * Get the live agent for a target session, opening the session again when it is
181
- * not currently running. The session is reopened on the preset it was created
182
- * with.
183
- * @param ctx - services of the calling agent.
184
- * @param sessionId - the target session.
185
- * @param callerAgent - the calling agent, whose model the reopened session inherits.
186
- * @returns the live or resumed Agent.
187
- */
188
- async function resolveTargetAgent(ctx, sessionId, callerAgent) {
320
+ /** Pending resumes are shared by plugin instances using the same agent service. */
321
+ const targetResumes = new WeakMap();
322
+
323
+ function checkSendTarget(sessionId, header, callerAgent) {
324
+ 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");
325
+ 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.`);
326
+ 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.`);
327
+ }
328
+
329
+ /** Read target metadata without opening a writable session or publishing an agent. */
330
+ async function inspectSendTarget(ctx, sessionId, exec) {
331
+ exec.signal?.throwIfAborted();
332
+ 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");
189
333
  const live = ctx.agents.get(sessionId);
190
- if (live !== void 0) return live;
334
+ if (live !== void 0) {
335
+ checkSendTarget(sessionId, live.session.header, exec.agent);
336
+ return { agent: live, header: live.session.header };
337
+ }
191
338
  const query = ctx.get("sessionQuery");
192
339
  if (query === void 0) throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: this DSH does not offer session lookup`);
193
340
  let record;
194
341
  try {
195
- record = (await query.listSessions()).find((entry) => String(entry.header.id) === sessionId);
342
+ // listSessions owns and releases its read resources; no handle escapes.
343
+ record = (await query.listSessions(exec.signal)).find((entry) => String(entry.header.id) === sessionId);
196
344
  } catch (error) {
197
345
  throw new Error(`session_send cannot read ${JSON.stringify(sessionId)}: ${error instanceof Error ? error.message : String(error)}`);
198
346
  }
347
+ exec.signal?.throwIfAborted();
199
348
  if (record === void 0) throw new Error(`session_send cannot find session ${JSON.stringify(sessionId)}: no open or saved session has that id`);
200
- if (record.header.cwd === void 0) throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: the saved session records no working directory`);
201
- const agentPresets = ctx.get("agentPresets");
202
- const presetId = record.header.agentPreset;
203
- const setup = agentPresets === void 0 || presetId === void 0 ? void 0 : async (agentCtx) => {
204
- await agentPresets.mount(agentCtx, presetId);
349
+ checkSendTarget(sessionId, record.header, exec.agent);
350
+ return { header: record.header };
351
+ }
352
+
353
+ /** Recheck after approval, then serialize resumes so concurrent sends share one agent. */
354
+ async function resolveTargetAgent(ctx, sessionId, exec) {
355
+ const agents = ctx.agents;
356
+ // Cordis creates a fresh traced proxy on each service read. Its exported
357
+ // original symbol gives stable identity; keep using the traced service for
358
+ // method calls so ownership and caller context are still preserved.
359
+ const serviceIdentity = agents[symbols.original] ?? agents;
360
+ let pending = targetResumes.get(serviceIdentity);
361
+ if (pending === void 0) targetResumes.set(serviceIdentity, pending = new Map());
362
+ const previous = pending.get(sessionId);
363
+ const operation = (async () => {
364
+ // A failed/cancelled earlier sender must not invalidate this sender's grant.
365
+ if (previous !== void 0) await previous.catch(() => {});
366
+ const inspected = await inspectSendTarget(ctx, sessionId, exec);
367
+ exec.signal?.throwIfAborted();
368
+ // Another host caller may have published the agent during the metadata read.
369
+ const live = agents.get(sessionId);
370
+ if (live !== void 0) {
371
+ checkSendTarget(sessionId, live.session.header, exec.agent);
372
+ return live;
373
+ }
374
+ const agentPresets = ctx.get("agentPresets");
375
+ const presetId = inspected.header.agentPreset;
376
+ const setup = agentPresets === void 0 || presetId === void 0 ? void 0 : async (agentCtx) => {
377
+ await agentPresets.mount(agentCtx, presetId);
378
+ };
379
+ const resumed = await agents.resume({
380
+ resumeSessionId: sessionId,
381
+ agentOptions: currentSelection(ctx, exec.agent),
382
+ signal: exec.signal,
383
+ ...setup === void 0 ? {} : { setup }
384
+ });
385
+ return resumed.agent;
386
+ })();
387
+ pending.set(sessionId, operation);
388
+ const release = () => {
389
+ if (pending.get(sessionId) === operation) pending.delete(sessionId);
205
390
  };
206
- const resumed = await ctx.agents.resume({
207
- resumeSessionId: sessionId,
208
- agentOptions: currentSelection(ctx, callerAgent),
209
- ...setup === void 0 ? {} : { setup }
210
- });
211
- return resumed.agent;
391
+ // Keep the queue slot until the actual operation settles, even if this
392
+ // caller stops waiting. Otherwise a later sender could bypass an active resume.
393
+ void operation.then(release, release);
394
+ if (previous !== void 0 && exec.signal !== void 0) {
395
+ const cancelled = Promise.withResolvers();
396
+ const onAbort = () => cancelled.reject(exec.signal.reason);
397
+ try {
398
+ exec.signal.addEventListener("abort", onAbort, { once: true });
399
+ if (exec.signal.aborted) onAbort();
400
+ await Promise.race([previous.catch(() => {}), cancelled.promise]);
401
+ } finally {
402
+ exec.signal.removeEventListener("abort", onAbort);
403
+ }
404
+ }
405
+ return await operation;
212
406
  }
213
407
  /**
214
408
  * Register `session_create` and `session_send`.
215
409
  * @param ctx - services of the agent this plugin was loaded for.
216
410
  */
217
411
  function apply(ctx) {
412
+ const sortByActivity = createActivitySorter(ctx);
413
+ // Optional capability; the same pure fold also works over a read-only full log.
414
+ if (typeof ctx.inject === "function") ctx.inject(["sessionProjections"], scope => {
415
+ scope.sessionProjections.register(receiptProjection);
416
+ });
218
417
  ctx.tools.register(defineTool({
219
418
  name: "session_create",
220
419
  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.",
@@ -222,7 +421,7 @@ function apply(ctx) {
222
421
  prompt: {
223
422
  type: "string",
224
423
  required: true,
225
- description: "The new session's first user message. Write it self-contained: the new session cannot see this conversation."
424
+ description: "The new session's first task, delivered with plugin provenance. Write it self-contained: the new session cannot see this conversation."
226
425
  },
227
426
  workspacePath: {
228
427
  type: "string",
@@ -230,11 +429,15 @@ function apply(ctx) {
230
429
  },
231
430
  title: {
232
431
  type: "string",
233
- description: "Optional title. Leave it out and the title is generated from the first message, exactly like a session the person creates by hand."
432
+ 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."
234
433
  },
235
434
  wait: {
236
435
  type: "boolean",
237
- description: "Wait for the new session's first turn to finish before returning. Defaults to false."
436
+ description: "Wait for the first message's recorded turn to end before returning. Defaults to false; bounded by timeoutMs."
437
+ },
438
+ timeoutMs: {
439
+ type: "number",
440
+ description: "Wait budget in milliseconds. Defaults to 60000, at most 300000. Timeout or caller cancellation only ends this wait."
238
441
  }
239
442
  },
240
443
  output: {
@@ -256,16 +459,26 @@ function apply(ctx) {
256
459
  },
257
460
  workspaceId: { type: "string" },
258
461
  workspacePath: { type: "string" },
259
- title: { type: "string" }
462
+ title: { type: "string" },
463
+ waited: { type: "boolean" },
464
+ completed: { type: "boolean" },
465
+ waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
466
+ elapsedMs: { type: "number" },
467
+ ...receiptProperties
260
468
  }
261
469
  },
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.
470
+ // rc.2 persists this projection on tool/result and exposes it as
471
+ // ToolResultNode.meta. The canonical value alone does not survive replay.
472
+ presentationMeta: (_args, value) => ({
473
+ sessionId: value.sessionId,
474
+ ...typeof value.title === "string" ? { title: value.title } : {}
475
+ }),
476
+ // Keep the receipt readable for clients without the session card.
264
477
  render: (_args, value) => [{
265
478
  type: "text",
266
- text: value.grouped === true
479
+ text: (value.grouped === true
267
480
  ? `Created session: ${sessionReference(value.title, value.sessionId)} in workspace ${value.workspacePath}`
268
- : `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`
481
+ : `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`) + `\n${receiptText(value)}`
269
482
  }]
270
483
  },
271
484
  async execute(args, exec) {
@@ -293,11 +506,14 @@ function apply(ctx) {
293
506
  const agentOptions = currentSelection(ctx, exec.agent);
294
507
  const agentPresets = ctx.get("agentPresets");
295
508
  const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
509
+ exec.signal?.throwIfAborted();
296
510
  const sessionId = brandString(`session-${randomUUID()}`);
297
511
  let handle;
298
512
  let attached = false;
513
+ let sent;
299
514
  try {
300
515
  handle = await ctx.agents.create({
516
+ signal: exec.signal,
301
517
  sessionId,
302
518
  agentOptions,
303
519
  meta: {
@@ -309,13 +525,18 @@ function apply(ctx) {
309
525
  await agentPresets.mount(agentCtx, presetId);
310
526
  } }
311
527
  });
528
+ exec.signal?.throwIfAborted();
312
529
  if (workspace !== void 0) {
313
530
  await workspace.attachSession(sessionId);
314
531
  attached = true;
315
532
  }
316
- const title = args.title === void 0 ? void 0 : args.title.trim();
317
- if (title !== void 0 && title !== "") ctx.sessionTitle.rename(handle.agent.session, title);
318
- handle.agent.followup(createUserMessage({
533
+ exec.signal?.throwIfAborted();
534
+ const title = args.title?.trim() || fallbackSessionTitle(prompt, fallbackTitleWords, fallbackTitleBytes);
535
+ // The public rename operation logs and pins the initial title. It
536
+ // does not change the first message's plugin provenance below.
537
+ ctx.sessionTitle.rename(handle.agent.session, title);
538
+ exec.signal?.throwIfAborted();
539
+ sent = createUserMessage({
319
540
  content: [{
320
541
  type: "text",
321
542
  text: prompt
@@ -324,8 +545,8 @@ function apply(ctx) {
324
545
  kind: "plugin",
325
546
  plugin: name
326
547
  }
327
- }));
328
- if (args.wait === true) await handle.agent.whenIdle();
548
+ });
549
+ handle.agent.followup(sent);
329
550
  } catch (error) {
330
551
  if (attached) try {
331
552
  await workspace.detachSession(sessionId);
@@ -335,8 +556,10 @@ function apply(ctx) {
335
556
  } catch {}
336
557
  throw error;
337
558
  }
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.
559
+ // Once delivered, the target owns its lifetime. Ending this observation
560
+ // must not detach its workspace or dispose its handle.
561
+ const waited = args.wait === true ? await observeReceipt(ctx, String(sessionId), sent.id, args.timeoutMs, exec.signal) : undefined;
562
+ // Read the accepted title after host normalization (or a manual rename).
340
563
  let currentTitle;
341
564
  try {
342
565
  // The service returns a title snapshot; the text lives on `.title`.
@@ -344,6 +567,8 @@ function apply(ctx) {
344
567
  } catch {}
345
568
  return {
346
569
  sessionId: String(sessionId),
570
+ messageId: sent.id,
571
+ ...waited === undefined ? deliveredReceipt(handle.agent, sent.id) : { waited: true, ...waited },
347
572
  grouped: workspace !== void 0,
348
573
  cwd,
349
574
  ...currentTitle === void 0 || currentTitle === "" ? {} : { title: String(currentTitle) },
@@ -374,7 +599,7 @@ function apply(ctx) {
374
599
  },
375
600
  timeoutMs: {
376
601
  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."
602
+ 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."
378
603
  }
379
604
  },
380
605
  output: {
@@ -392,17 +617,15 @@ function apply(ctx) {
392
617
  },
393
618
  waited: { type: "boolean" },
394
619
  completed: { type: "boolean" },
620
+ waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
395
621
  elapsedMs: { type: "number" },
396
- output: { type: "string" }
622
+ ...receiptProperties
397
623
  }
398
624
  },
625
+ presentationMeta: (_args, value) => ({ sessionId: value.sessionId, messageId: value.messageId }),
399
626
  render: (_args, value) => [{
400
627
  type: "text",
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`
628
+ text: receiptText(value)
406
629
  }]
407
630
  },
408
631
  async execute(args, exec) {
@@ -411,15 +634,14 @@ function apply(ctx) {
411
634
  if (requested === "") throw new Error("session_send needs a session id");
412
635
  const message = args.message.trim();
413
636
  if (message === "") throw new Error("session_send needs a message");
414
- const target = await resolveTargetAgent(ctx, requested, exec.agent);
637
+ await inspectSendTarget(ctx, requested, exec);
638
+ await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(requested)}: ${message.slice(0, 120)}`);
639
+ const target = await resolveTargetAgent(ctx, requested, exec);
640
+ exec.signal?.throwIfAborted();
415
641
  const targetId = String(target.id);
416
- if (targetId === String(exec.agent.id)) throw new Error("session_send cannot send to its own session: use the current conversation instead");
417
- const depth = target.session.header.delegationDepth ?? 0;
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)}`);
422
- target.followup(createUserMessage({
642
+ if (targetId !== requested) throw new Error("session_send resolved a different target; no message was sent");
643
+ checkSendTarget(targetId, target.session.header, exec.agent);
644
+ const sent = createUserMessage({
423
645
  content: [{
424
646
  type: "text",
425
647
  text: message
@@ -428,36 +650,27 @@ function apply(ctx) {
428
650
  kind: "plugin",
429
651
  plugin: name
430
652
  }
431
- }));
653
+ });
654
+ target.followup(sent);
432
655
  if (args.wait !== true) return {
433
656
  sessionId: targetId,
657
+ messageId: sent.id,
658
+ ...deliveredReceipt(target, sent.id),
434
659
  cwd: String(target.session.header.cwd ?? "")
435
660
  };
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);
661
+ const result = await observeReceipt(ctx, targetId, sent.id, args.timeoutMs, exec.signal);
448
662
  return {
449
663
  sessionId: targetId,
664
+ messageId: sent.id,
450
665
  cwd: String(target.session.header.cwd ?? ""),
451
666
  waited: true,
452
- completed: !timedOut,
453
- elapsedMs: Date.now() - startedAt,
454
- ...answer === void 0 ? {} : { output: answer }
667
+ ...result
455
668
  };
456
669
  }
457
670
  }));
458
671
  ctx.tools.register(defineTool({
459
672
  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.",
673
+ 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.",
461
674
  parameters: {
462
675
  limit: {
463
676
  type: "number",
@@ -522,23 +735,21 @@ function apply(ctx) {
522
735
  const requested = args.limit === void 0 ? 20 : Math.trunc(args.limit);
523
736
  const limit = requested < 1 ? 1 : requested > 100 ? 100 : requested;
524
737
  const self = exec.agent === void 0 ? undefined : String(exec.agent.id);
525
- const records = await query.listSessions();
738
+ const records = await query.listSessions(exec.signal);
739
+ const visible = records.filter(({ header }) => (header.delegationDepth ?? 0) <= 0 && header.origin !== "subagent");
740
+ const ordered = await sortByActivity(visible, exec.signal);
526
741
  const listed = [];
527
- let total = 0;
528
- for (const record of records) {
742
+ for (const record of ordered.slice(0, limit)) {
743
+ exec.signal?.throwIfAborted();
529
744
  const header = record.header;
530
745
  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
746
  let title;
537
747
  try {
538
748
  // Title reads return a snapshot, not a string: the text lives on
539
749
  // `.title`, exactly like the title service the create path uses.
540
- title = (await query.readTitle(sessionId))?.title;
750
+ title = (await query.readTitle(sessionId, exec.signal))?.title;
541
751
  } catch {}
752
+ exec.signal?.throwIfAborted();
542
753
  listed.push({
543
754
  sessionId,
544
755
  ...title === void 0 || title === "" ? {} : { title: String(title) },
@@ -547,18 +758,22 @@ function apply(ctx) {
547
758
  ...sessionId === self ? { current: true } : {}
548
759
  });
549
760
  }
550
- return { sessions: listed, total };
761
+ return { sessions: listed, total: records.length };
551
762
  }
552
763
  }));
553
764
  ctx.tools.register(defineTool({
554
765
  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.",
766
+ 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.",
556
767
  parameters: {
557
768
  sessionId: {
558
769
  type: "string",
559
770
  required: true,
560
771
  description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
561
772
  },
773
+ messageId: {
774
+ type: "string",
775
+ description: "The exact messageId returned with sessionId by session_send or session_create, including after timeout. Omit only for a session overview."
776
+ },
562
777
  timeoutMs: {
563
778
  type: "number",
564
779
  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."
@@ -581,15 +796,18 @@ function apply(ctx) {
581
796
  type: "boolean",
582
797
  required: true
583
798
  },
799
+ waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
584
800
  elapsedMs: { type: "number" },
585
- output: { type: "string" }
801
+ scope: { type: "string", enum: ["message", "sessionOverview"] },
802
+ ...receiptProperties
586
803
  }
587
804
  },
588
805
  render: (_args, value) => [{
589
806
  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`
807
+ text: value.scope === "message" ? receiptText(value) :
808
+ `Session overview for ${value.sessionId} (not a message result): ` +
809
+ (waitNotice(value) ?? (value.running ? "running" : "idle")) +
810
+ (value.output === undefined ? "" : `\nLatest session answer, not attributed to any receipt:\n${value.output}`)
593
811
  }]
594
812
  },
595
813
  async execute(args, exec) {
@@ -597,36 +815,33 @@ function apply(ctx) {
597
815
  if (requested === "") throw new Error("session_wait needs a session id");
598
816
  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
817
  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);
818
+ if (args.messageId !== undefined) {
819
+ const messageId = args.messageId.trim();
820
+ if (messageId === "") throw new Error("session_wait needs a non-empty messageId, or omit it for a session overview");
821
+ const result = await observeReceipt(ctx, requested, messageId, args.timeoutMs, exec.signal);
608
822
  return {
609
- sessionId: requested,
610
- running: false,
611
- completed: true,
612
- elapsedMs: 0,
613
- ...answer === void 0 ? {} : { output: answer }
823
+ sessionId: requested, messageId, scope: "message", running: ctx.agents.get(requested)?.status === "running",
824
+ ...result
614
825
  };
615
826
  }
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);
827
+
828
+ const result = await observeWait(args.timeoutMs, exec.signal, async (signal, onCleanup) => {
829
+ if (target === undefined) {
830
+ const query = ctx.get("sessionQuery");
831
+ if (query === undefined) throw new Error(`session_wait cannot check ${JSON.stringify(requested)}: this DSH does not offer session lookup`);
832
+ const known = (await query.listSessions(signal)).some(entry => String(entry.header.id) === requested);
833
+ signal.throwIfAborted();
834
+ if (!known) throw new Error(`session_wait cannot find session ${JSON.stringify(requested)}: no open or saved session has that id`);
835
+ } else await target.whenIdle();
836
+ signal.throwIfAborted();
837
+ const answer = await readFinalAnswer(ctx, requested, signal, onCleanup);
838
+ return answer === undefined ? {} : { output: answer };
839
+ });
624
840
  return {
625
841
  sessionId: requested,
626
- running: true,
627
- completed: !timedOut,
628
- elapsedMs: Date.now() - startedAt,
629
- ...answer === void 0 ? {} : { output: answer }
842
+ scope: "sessionOverview",
843
+ running: target?.status === "running",
844
+ ...result
630
845
  };
631
846
  }
632
847
  }));