@ryuu-64/dsh-session-tools 0.5.4 → 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/README.md +117 -13
- package/lib/client.js +24 -40
- package/lib/index.js +354 -168
- package/lib/message-receipts.js +121 -0
- package/lib/session-activity.js +123 -0
- package/package.json +78 -2
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
|
|
46
|
-
*
|
|
47
|
-
*
|
|
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,
|
|
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
|
-
* @
|
|
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
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
-
|
|
63
|
-
if (policy
|
|
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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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
|
|
149
|
-
if (
|
|
150
|
-
const
|
|
151
|
-
if (
|
|
152
|
-
|
|
153
|
-
|
|
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,77 +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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
* messages still waiting, and each carries its own id.
|
|
187
|
-
* @param agent - the live target agent.
|
|
188
|
-
* @param messageId - the id of the message we just queued.
|
|
189
|
-
* @param budgetMs - how long to keep polling before giving up.
|
|
190
|
-
* @returns true when the message was taken, false on timeout.
|
|
191
|
-
*/
|
|
192
|
-
async function waitUntilConsumed(agent, messageId, budgetMs) {
|
|
193
|
-
const deadline = Date.now() + budgetMs;
|
|
194
|
-
const stillQueued = () => {
|
|
195
|
-
const pending = agent.inbox?.nextTurn;
|
|
196
|
-
// An unrecognisable inbox shape cannot prove anything; report a timeout
|
|
197
|
-
// rather than a completion we did not observe.
|
|
198
|
-
if (!Array.isArray(pending)) return undefined;
|
|
199
|
-
return pending.some((queued) => queued?.id === messageId);
|
|
200
|
-
};
|
|
201
|
-
for (;;) {
|
|
202
|
-
const queued = stillQueued();
|
|
203
|
-
if (queued === false && agent.status !== "running") return true;
|
|
204
|
-
if (queued === undefined) return false;
|
|
205
|
-
if (Date.now() >= deadline) return false;
|
|
206
|
-
await new Promise((resolve) => {
|
|
207
|
-
setTimeout(resolve, 25);
|
|
208
|
-
});
|
|
209
|
-
}
|
|
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.`);
|
|
210
327
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
* @param sessionId - the target session.
|
|
217
|
-
* @param callerAgent - the calling agent, whose model the reopened session inherits.
|
|
218
|
-
* @returns the live or resumed Agent.
|
|
219
|
-
*/
|
|
220
|
-
async function resolveTargetAgent(ctx, sessionId, callerAgent) {
|
|
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");
|
|
221
333
|
const live = ctx.agents.get(sessionId);
|
|
222
|
-
if (live !== void 0)
|
|
334
|
+
if (live !== void 0) {
|
|
335
|
+
checkSendTarget(sessionId, live.session.header, exec.agent);
|
|
336
|
+
return { agent: live, header: live.session.header };
|
|
337
|
+
}
|
|
223
338
|
const query = ctx.get("sessionQuery");
|
|
224
339
|
if (query === void 0) throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: this DSH does not offer session lookup`);
|
|
225
340
|
let record;
|
|
226
341
|
try {
|
|
227
|
-
|
|
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);
|
|
228
344
|
} catch (error) {
|
|
229
345
|
throw new Error(`session_send cannot read ${JSON.stringify(sessionId)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
230
346
|
}
|
|
347
|
+
exec.signal?.throwIfAborted();
|
|
231
348
|
if (record === void 0) throw new Error(`session_send cannot find session ${JSON.stringify(sessionId)}: no open or saved session has that id`);
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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);
|
|
237
390
|
};
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
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;
|
|
244
406
|
}
|
|
245
407
|
/**
|
|
246
408
|
* Register `session_create` and `session_send`.
|
|
247
409
|
* @param ctx - services of the agent this plugin was loaded for.
|
|
248
410
|
*/
|
|
249
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
|
+
});
|
|
250
417
|
ctx.tools.register(defineTool({
|
|
251
418
|
name: "session_create",
|
|
252
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.",
|
|
@@ -254,7 +421,7 @@ function apply(ctx) {
|
|
|
254
421
|
prompt: {
|
|
255
422
|
type: "string",
|
|
256
423
|
required: true,
|
|
257
|
-
description: "The new session's first
|
|
424
|
+
description: "The new session's first task, delivered with plugin provenance. Write it self-contained: the new session cannot see this conversation."
|
|
258
425
|
},
|
|
259
426
|
workspacePath: {
|
|
260
427
|
type: "string",
|
|
@@ -262,11 +429,15 @@ function apply(ctx) {
|
|
|
262
429
|
},
|
|
263
430
|
title: {
|
|
264
431
|
type: "string",
|
|
265
|
-
description: "Optional title.
|
|
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."
|
|
266
433
|
},
|
|
267
434
|
wait: {
|
|
268
435
|
type: "boolean",
|
|
269
|
-
description: "Wait for the
|
|
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."
|
|
270
441
|
}
|
|
271
442
|
},
|
|
272
443
|
output: {
|
|
@@ -288,16 +459,26 @@ function apply(ctx) {
|
|
|
288
459
|
},
|
|
289
460
|
workspaceId: { type: "string" },
|
|
290
461
|
workspacePath: { type: "string" },
|
|
291
|
-
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
|
|
292
468
|
}
|
|
293
469
|
},
|
|
294
|
-
//
|
|
295
|
-
//
|
|
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.
|
|
296
477
|
render: (_args, value) => [{
|
|
297
478
|
type: "text",
|
|
298
|
-
text: value.grouped === true
|
|
479
|
+
text: (value.grouped === true
|
|
299
480
|
? `Created session: ${sessionReference(value.title, value.sessionId)} in workspace ${value.workspacePath}`
|
|
300
|
-
: `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`
|
|
481
|
+
: `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`) + `\n${receiptText(value)}`
|
|
301
482
|
}]
|
|
302
483
|
},
|
|
303
484
|
async execute(args, exec) {
|
|
@@ -325,11 +506,14 @@ function apply(ctx) {
|
|
|
325
506
|
const agentOptions = currentSelection(ctx, exec.agent);
|
|
326
507
|
const agentPresets = ctx.get("agentPresets");
|
|
327
508
|
const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
|
|
509
|
+
exec.signal?.throwIfAborted();
|
|
328
510
|
const sessionId = brandString(`session-${randomUUID()}`);
|
|
329
511
|
let handle;
|
|
330
512
|
let attached = false;
|
|
513
|
+
let sent;
|
|
331
514
|
try {
|
|
332
515
|
handle = await ctx.agents.create({
|
|
516
|
+
signal: exec.signal,
|
|
333
517
|
sessionId,
|
|
334
518
|
agentOptions,
|
|
335
519
|
meta: {
|
|
@@ -341,13 +525,18 @@ function apply(ctx) {
|
|
|
341
525
|
await agentPresets.mount(agentCtx, presetId);
|
|
342
526
|
} }
|
|
343
527
|
});
|
|
528
|
+
exec.signal?.throwIfAborted();
|
|
344
529
|
if (workspace !== void 0) {
|
|
345
530
|
await workspace.attachSession(sessionId);
|
|
346
531
|
attached = true;
|
|
347
532
|
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
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({
|
|
351
540
|
content: [{
|
|
352
541
|
type: "text",
|
|
353
542
|
text: prompt
|
|
@@ -356,8 +545,8 @@ function apply(ctx) {
|
|
|
356
545
|
kind: "plugin",
|
|
357
546
|
plugin: name
|
|
358
547
|
}
|
|
359
|
-
})
|
|
360
|
-
|
|
548
|
+
});
|
|
549
|
+
handle.agent.followup(sent);
|
|
361
550
|
} catch (error) {
|
|
362
551
|
if (attached) try {
|
|
363
552
|
await workspace.detachSession(sessionId);
|
|
@@ -367,8 +556,10 @@ function apply(ctx) {
|
|
|
367
556
|
} catch {}
|
|
368
557
|
throw error;
|
|
369
558
|
}
|
|
370
|
-
//
|
|
371
|
-
//
|
|
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).
|
|
372
563
|
let currentTitle;
|
|
373
564
|
try {
|
|
374
565
|
// The service returns a title snapshot; the text lives on `.title`.
|
|
@@ -376,6 +567,8 @@ function apply(ctx) {
|
|
|
376
567
|
} catch {}
|
|
377
568
|
return {
|
|
378
569
|
sessionId: String(sessionId),
|
|
570
|
+
messageId: sent.id,
|
|
571
|
+
...waited === undefined ? deliveredReceipt(handle.agent, sent.id) : { waited: true, ...waited },
|
|
379
572
|
grouped: workspace !== void 0,
|
|
380
573
|
cwd,
|
|
381
574
|
...currentTitle === void 0 || currentTitle === "" ? {} : { title: String(currentTitle) },
|
|
@@ -406,7 +599,7 @@ function apply(ctx) {
|
|
|
406
599
|
},
|
|
407
600
|
timeoutMs: {
|
|
408
601
|
type: "number",
|
|
409
|
-
description: "How long to
|
|
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."
|
|
410
603
|
}
|
|
411
604
|
},
|
|
412
605
|
output: {
|
|
@@ -424,17 +617,15 @@ function apply(ctx) {
|
|
|
424
617
|
},
|
|
425
618
|
waited: { type: "boolean" },
|
|
426
619
|
completed: { type: "boolean" },
|
|
620
|
+
waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
|
|
427
621
|
elapsedMs: { type: "number" },
|
|
428
|
-
|
|
622
|
+
...receiptProperties
|
|
429
623
|
}
|
|
430
624
|
},
|
|
625
|
+
presentationMeta: (_args, value) => ({ sessionId: value.sessionId, messageId: value.messageId }),
|
|
431
626
|
render: (_args, value) => [{
|
|
432
627
|
type: "text",
|
|
433
|
-
text: value
|
|
434
|
-
? `Delivered to session ${value.sessionId}`
|
|
435
|
-
: value.completed === true
|
|
436
|
-
? `Session ${value.sessionId} finished (${Math.round((value.elapsedMs ?? 0) / 1000)}s):\n${value.output ?? "(no text answer)"}`
|
|
437
|
-
: `Delivered to session ${value.sessionId}; still working after ${Math.round((value.elapsedMs ?? 0) / 1000)}s`
|
|
628
|
+
text: receiptText(value)
|
|
438
629
|
}]
|
|
439
630
|
},
|
|
440
631
|
async execute(args, exec) {
|
|
@@ -443,14 +634,13 @@ function apply(ctx) {
|
|
|
443
634
|
if (requested === "") throw new Error("session_send needs a session id");
|
|
444
635
|
const message = args.message.trim();
|
|
445
636
|
if (message === "") throw new Error("session_send needs a message");
|
|
446
|
-
|
|
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();
|
|
447
641
|
const targetId = String(target.id);
|
|
448
|
-
if (targetId
|
|
449
|
-
|
|
450
|
-
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.`);
|
|
451
|
-
// Ask before writing into another session: the person should see a message
|
|
452
|
-
// arrive in a conversation they are not looking at.
|
|
453
|
-
await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(targetId)}: ${message.slice(0, 120)}`);
|
|
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);
|
|
454
644
|
const sent = createUserMessage({
|
|
455
645
|
content: [{
|
|
456
646
|
type: "text",
|
|
@@ -464,29 +654,23 @@ function apply(ctx) {
|
|
|
464
654
|
target.followup(sent);
|
|
465
655
|
if (args.wait !== true) return {
|
|
466
656
|
sessionId: targetId,
|
|
657
|
+
messageId: sent.id,
|
|
658
|
+
...deliveredReceipt(target, sent.id),
|
|
467
659
|
cwd: String(target.session.header.cwd ?? "")
|
|
468
660
|
};
|
|
469
|
-
|
|
470
|
-
// look idle the instant the message is queued, so an idle wait alone
|
|
471
|
-
// would return the PREVIOUS answer; wait until this message has left the
|
|
472
|
-
// inbox first. Both signals are public Agent surface.
|
|
473
|
-
const startedAt = Date.now();
|
|
474
|
-
const timeoutMs = waitBudgetMs(args.timeoutMs);
|
|
475
|
-
const consumed = await waitUntilConsumed(target, sent.id, timeoutMs);
|
|
476
|
-
const answer = await readFinalAnswer(ctx, targetId);
|
|
661
|
+
const result = await observeReceipt(ctx, targetId, sent.id, args.timeoutMs, exec.signal);
|
|
477
662
|
return {
|
|
478
663
|
sessionId: targetId,
|
|
664
|
+
messageId: sent.id,
|
|
479
665
|
cwd: String(target.session.header.cwd ?? ""),
|
|
480
666
|
waited: true,
|
|
481
|
-
|
|
482
|
-
elapsedMs: Date.now() - startedAt,
|
|
483
|
-
...answer === void 0 ? {} : { output: answer }
|
|
667
|
+
...result
|
|
484
668
|
};
|
|
485
669
|
}
|
|
486
670
|
}));
|
|
487
671
|
ctx.tools.register(defineTool({
|
|
488
672
|
name: "list_sessions",
|
|
489
|
-
description: "List the sessions the person can see,
|
|
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.",
|
|
490
674
|
parameters: {
|
|
491
675
|
limit: {
|
|
492
676
|
type: "number",
|
|
@@ -551,23 +735,21 @@ function apply(ctx) {
|
|
|
551
735
|
const requested = args.limit === void 0 ? 20 : Math.trunc(args.limit);
|
|
552
736
|
const limit = requested < 1 ? 1 : requested > 100 ? 100 : requested;
|
|
553
737
|
const self = exec.agent === void 0 ? undefined : String(exec.agent.id);
|
|
554
|
-
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);
|
|
555
741
|
const listed = [];
|
|
556
|
-
|
|
557
|
-
|
|
742
|
+
for (const record of ordered.slice(0, limit)) {
|
|
743
|
+
exec.signal?.throwIfAborted();
|
|
558
744
|
const header = record.header;
|
|
559
745
|
const sessionId = String(header.id);
|
|
560
|
-
total += 1;
|
|
561
|
-
// Subagent sessions are someone else's working state, not a target the
|
|
562
|
-
// person can be asked about; the count still reports them.
|
|
563
|
-
if ((header.delegationDepth ?? 0) > 0 || header.origin === "subagent") continue;
|
|
564
|
-
if (listed.length >= limit) continue;
|
|
565
746
|
let title;
|
|
566
747
|
try {
|
|
567
748
|
// Title reads return a snapshot, not a string: the text lives on
|
|
568
749
|
// `.title`, exactly like the title service the create path uses.
|
|
569
|
-
title = (await query.readTitle(sessionId))?.title;
|
|
750
|
+
title = (await query.readTitle(sessionId, exec.signal))?.title;
|
|
570
751
|
} catch {}
|
|
752
|
+
exec.signal?.throwIfAborted();
|
|
571
753
|
listed.push({
|
|
572
754
|
sessionId,
|
|
573
755
|
...title === void 0 || title === "" ? {} : { title: String(title) },
|
|
@@ -576,18 +758,22 @@ function apply(ctx) {
|
|
|
576
758
|
...sessionId === self ? { current: true } : {}
|
|
577
759
|
});
|
|
578
760
|
}
|
|
579
|
-
return { sessions: listed, total };
|
|
761
|
+
return { sessions: listed, total: records.length };
|
|
580
762
|
}
|
|
581
763
|
}));
|
|
582
764
|
ctx.tools.register(defineTool({
|
|
583
765
|
name: "session_wait",
|
|
584
|
-
description: "
|
|
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.",
|
|
585
767
|
parameters: {
|
|
586
768
|
sessionId: {
|
|
587
769
|
type: "string",
|
|
588
770
|
required: true,
|
|
589
771
|
description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
|
|
590
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
|
+
},
|
|
591
777
|
timeoutMs: {
|
|
592
778
|
type: "number",
|
|
593
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."
|
|
@@ -610,15 +796,18 @@ function apply(ctx) {
|
|
|
610
796
|
type: "boolean",
|
|
611
797
|
required: true
|
|
612
798
|
},
|
|
799
|
+
waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
|
|
613
800
|
elapsedMs: { type: "number" },
|
|
614
|
-
|
|
801
|
+
scope: { type: "string", enum: ["message", "sessionOverview"] },
|
|
802
|
+
...receiptProperties
|
|
615
803
|
}
|
|
616
804
|
},
|
|
617
805
|
render: (_args, value) => [{
|
|
618
806
|
type: "text",
|
|
619
|
-
text: value.
|
|
620
|
-
|
|
621
|
-
|
|
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}`)
|
|
622
811
|
}]
|
|
623
812
|
},
|
|
624
813
|
async execute(args, exec) {
|
|
@@ -626,36 +815,33 @@ function apply(ctx) {
|
|
|
626
815
|
if (requested === "") throw new Error("session_wait needs a session id");
|
|
627
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");
|
|
628
817
|
const target = ctx.agents.get(requested);
|
|
629
|
-
if (
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
const
|
|
633
|
-
if (query === void 0) throw new Error(`session_wait cannot check ${JSON.stringify(requested)}: this DSH does not offer session lookup`);
|
|
634
|
-
const known = (await query.listSessions()).some((entry) => String(entry.header.id) === requested);
|
|
635
|
-
if (!known) throw new Error(`session_wait cannot find session ${JSON.stringify(requested)}: no open or saved session has that id`);
|
|
636
|
-
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);
|
|
637
822
|
return {
|
|
638
|
-
sessionId: requested,
|
|
639
|
-
|
|
640
|
-
completed: true,
|
|
641
|
-
elapsedMs: 0,
|
|
642
|
-
...answer === void 0 ? {} : { output: answer }
|
|
823
|
+
sessionId: requested, messageId, scope: "message", running: ctx.agents.get(requested)?.status === "running",
|
|
824
|
+
...result
|
|
643
825
|
};
|
|
644
826
|
}
|
|
645
|
-
|
|
646
|
-
const
|
|
647
|
-
target
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
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
|
+
});
|
|
653
840
|
return {
|
|
654
841
|
sessionId: requested,
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
...answer === void 0 ? {} : { output: answer }
|
|
842
|
+
scope: "sessionOverview",
|
|
843
|
+
running: target?.status === "running",
|
|
844
|
+
...result
|
|
659
845
|
};
|
|
660
846
|
}
|
|
661
847
|
}));
|