@ryuu-64/dsh-session-tools 0.5.4 → 0.7.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 +40 -74
- package/lib/client.js +38 -42
- package/lib/index.js +372 -200
- package/lib/message-receipts.js +121 -0
- package/lib/session-activity.js +135 -0
- package/lib/session-discovery.js +204 -0
- package/package.json +99 -11
package/lib/index.js
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
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, readSlots } from "./session-activity.js";
|
|
12
|
+
import { createSessionDiscovery } from "./session-discovery.js";
|
|
7
13
|
|
|
8
|
-
/** Stable Loader identity. */
|
|
14
|
+
/** Stable Loader identity and producer-owned message source (V3 and V4). */
|
|
9
15
|
const name = "tool-session";
|
|
10
16
|
/** Nothing to configure. */
|
|
11
17
|
const Config = z.object({});
|
|
18
|
+
// Public fallback helper, using the shipped dsh-base 0.1.5-rc.2 limits.
|
|
19
|
+
// SessionTitleService.rename still enforces the host's accepted-title limit.
|
|
20
|
+
const fallbackTitleWords = 5;
|
|
21
|
+
const fallbackTitleBytes = 40;
|
|
12
22
|
/** Host services this tool needs: where it registers tools, and what it creates a session with. */
|
|
13
23
|
const inject = [
|
|
14
24
|
"tools",
|
|
@@ -42,31 +52,41 @@ function sessionReference(title, sessionId) {
|
|
|
42
52
|
return label === "" ? sessionId : `${label} · ${sessionId}`;
|
|
43
53
|
}
|
|
44
54
|
/**
|
|
45
|
-
* Ask
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* same as refusing, so the action proceeds.
|
|
55
|
+
* Ask before touching another session, except for the explicit full-access
|
|
56
|
+
* preset. Sandbox and approval are independent policies: `never` alone denies
|
|
57
|
+
* approval requests, it does not grant permission.
|
|
49
58
|
* @param ctx - services of the calling agent.
|
|
50
|
-
* @param exec - the running tool execution,
|
|
59
|
+
* @param exec - the running tool execution, including its cancellation signal.
|
|
51
60
|
* @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.
|
|
61
|
+
* @throws when permission cannot be established or the request is not allowed.
|
|
54
62
|
*/
|
|
55
63
|
async function requireApproval(ctx, exec, reason) {
|
|
64
|
+
const cancelled = () => {
|
|
65
|
+
if (exec.signal?.aborted) throw new Error(`the tool was cancelled, so ${reason} was not done`);
|
|
66
|
+
};
|
|
67
|
+
cancelled();
|
|
56
68
|
const approval = ctx.get("approval");
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
69
|
+
const sandboxPolicy = ctx.get("sandboxPolicy");
|
|
70
|
+
if (typeof approval?.overrideOf !== "function" || typeof approval?.request !== "function" || typeof sandboxPolicy?.resolve !== "function") {
|
|
71
|
+
throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
|
|
72
|
+
}
|
|
73
|
+
const session = exec.agent.session;
|
|
74
|
+
const mode = sandboxPolicy.resolve({ session })?.mode;
|
|
75
|
+
const policy = approval.overrideOf(session) ?? approval.config?.policy ?? "ask";
|
|
76
|
+
if (!["read-only", "workspace-write", "danger-full-access"].includes(mode) || !["ask", "never"].includes(policy)) {
|
|
77
|
+
throw new Error(`this DSH cannot establish permission, so ${reason} was not done`);
|
|
61
78
|
}
|
|
62
|
-
|
|
63
|
-
if (policy
|
|
79
|
+
cancelled();
|
|
80
|
+
if (mode === "danger-full-access" && policy === "never") return;
|
|
64
81
|
const outcome = await approval.request({
|
|
65
82
|
agent: exec.agent,
|
|
66
83
|
toolName: exec.name,
|
|
67
84
|
callId: exec.callId,
|
|
68
|
-
reason
|
|
85
|
+
reason,
|
|
86
|
+
signal: exec.signal
|
|
69
87
|
});
|
|
88
|
+
// A late answer must not revive a tool execution that has been cancelled.
|
|
89
|
+
cancelled();
|
|
70
90
|
if (outcome === "allowed-once") return;
|
|
71
91
|
throw new Error(
|
|
72
92
|
outcome === "rejected"
|
|
@@ -129,29 +149,151 @@ function waitBudgetMs(requested) {
|
|
|
129
149
|
const DEFAULT_MS = 60_000;
|
|
130
150
|
const MAX_MS = 300_000;
|
|
131
151
|
if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return DEFAULT_MS;
|
|
132
|
-
return Math.min(Math.trunc(requested), MAX_MS);
|
|
152
|
+
return Math.max(1, Math.min(Math.trunc(requested), MAX_MS));
|
|
133
153
|
}
|
|
134
|
-
/**
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
154
|
+
/** Own only this observation: never forward its abort signal to a target agent. */
|
|
155
|
+
async function observeWait(requested, callerSignal, observe) {
|
|
156
|
+
const startedAt = Date.now();
|
|
157
|
+
const controller = new AbortController();
|
|
158
|
+
const cleanups = new Set();
|
|
159
|
+
const stopped = Promise.withResolvers();
|
|
160
|
+
let status;
|
|
161
|
+
const stop = (reason) => {
|
|
162
|
+
if (status !== undefined) return;
|
|
163
|
+
status = reason;
|
|
164
|
+
stopped.resolve({ waitStatus: reason, completed: false });
|
|
165
|
+
controller.abort();
|
|
166
|
+
};
|
|
167
|
+
const onAbort = () => stop("callerCancelled");
|
|
168
|
+
let timer;
|
|
169
|
+
try {
|
|
170
|
+
callerSignal?.addEventListener("abort", onAbort, { once: true });
|
|
171
|
+
if (callerSignal?.aborted) onAbort();
|
|
172
|
+
else timer = setTimeout(() => stop("timedOut"), waitBudgetMs(requested));
|
|
173
|
+
const result = await Promise.race([
|
|
174
|
+
stopped.promise,
|
|
175
|
+
(async () => {
|
|
176
|
+
controller.signal.throwIfAborted();
|
|
177
|
+
const value = await observe(controller.signal, (cleanup) => cleanups.add(cleanup));
|
|
178
|
+
controller.signal.throwIfAborted();
|
|
179
|
+
return { waitStatus: "completed", completed: true, ...value };
|
|
180
|
+
})()
|
|
181
|
+
]);
|
|
182
|
+
return { ...result, elapsedMs: Date.now() - startedAt };
|
|
183
|
+
} finally {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
callerSignal?.removeEventListener("abort", onAbort);
|
|
186
|
+
// This also releases an outstanding polling timer or cancellable log read.
|
|
187
|
+
controller.abort();
|
|
188
|
+
await Promise.all([...cleanups].map(cleanup => cleanup()));
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Snapshot the delivery itself, including reentrant claims/removals in followup. */
|
|
193
|
+
function deliveredReceipt(agent, messageId) {
|
|
194
|
+
try {
|
|
195
|
+
const events = agent.session.snapshotEvents?.();
|
|
196
|
+
if (events !== undefined) {
|
|
197
|
+
const result = messageReceipt(foldReceipts(events, agent.session.inheritedEventCount), messageId, events);
|
|
198
|
+
if (result.messageStatus !== "unknown") return result;
|
|
199
|
+
}
|
|
200
|
+
if ([agent.inbox?.nextTurn, agent.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) return { messageStatus: "queued", completed: false };
|
|
201
|
+
} catch {}
|
|
202
|
+
return { messageStatus: "unknown", completed: false, attributionNote: "Delivery returned, but this host does not provide reliable message attribution." };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Read one exact message receipt. Quiet or a missing queue entry proves nothing. */
|
|
206
|
+
async function waitForReceipt(ctx, sessionId, messageId, signal, onCleanup, onProgress) {
|
|
207
|
+
for (;;) {
|
|
208
|
+
signal.throwIfAborted();
|
|
209
|
+
const log = await readSessionLog(ctx, sessionId, signal, onCleanup);
|
|
210
|
+
const target = ctx.agents.get(sessionId);
|
|
211
|
+
const cached = log.session !== undefined && target?.session === log.session ? ctx.get?.("sessionProjections")?.stateOf?.(log.session, receiptProjectionKey) : undefined;
|
|
212
|
+
const state = cached !== undefined && cached.seq === (log.events.at(-1)?.seq ?? -1) ? cached : foldReceipts(log.events, log.inheritedEventCount);
|
|
213
|
+
let value = messageReceipt(state, messageId, log.events);
|
|
214
|
+
// Pending live input is positive queue evidence even on a host without
|
|
215
|
+
// durable inbox events. Its later disappearance will NEVER imply success.
|
|
216
|
+
if (value.messageStatus === "unknown" && [target?.inbox?.nextTurn, target?.inbox?.nextStep].some(list => Array.isArray(list) && list.some(message => message.id === messageId))) {
|
|
217
|
+
value = { messageStatus: "queued", completed: false };
|
|
218
|
+
}
|
|
219
|
+
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." };
|
|
220
|
+
onProgress(value);
|
|
221
|
+
if (!["queued", "delivered"].includes(value.messageStatus) || target === undefined) return value;
|
|
222
|
+
await delay(25, undefined, { signal });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Preserve the last receipt state on timeout/caller cancellation, never its output. */
|
|
227
|
+
async function observeReceipt(ctx, sessionId, messageId, requested, callerSignal) {
|
|
228
|
+
let latest = { messageStatus: "unknown", completed: false };
|
|
229
|
+
const result = await observeWait(requested, callerSignal, (signal, onCleanup) =>
|
|
230
|
+
waitForReceipt(ctx, sessionId, messageId, signal, onCleanup, value => { latest = value; }));
|
|
231
|
+
if (result.waitStatus === "completed") return result;
|
|
232
|
+
const { output, ...receipt } = latest;
|
|
233
|
+
return { ...receipt, ...result };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const receiptProperties = {
|
|
237
|
+
messageId: { type: "string" },
|
|
238
|
+
messageStatus: { type: "string", enum: ["queued", "delivered", "turnCompleted", "discarded", "cancelled", "blocked", "failed", "interrupted", "incomplete", "unknown"] },
|
|
239
|
+
turn: { type: "number" },
|
|
240
|
+
turnEndKind: { type: "string" },
|
|
241
|
+
attributionNote: { type: "string" },
|
|
242
|
+
output: { type: "string" }
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
function receiptText(value) {
|
|
246
|
+
const receipt = `Receipt: sessionId=${value.sessionId}, messageId=${value.messageId}`;
|
|
247
|
+
const notice = waitNotice(value);
|
|
248
|
+
return `${receipt}\nMessage status: ${value.messageStatus ?? "queued"}${value.turn === undefined ? "" : `; turn ${value.turn}`}.` +
|
|
249
|
+
(value.messageStatus === "turnCompleted" ? " The recorded turn completed; this does not verify the business task succeeded." : "") +
|
|
250
|
+
(value.attributionNote ? `\n${value.attributionNote}` : "") + (notice ? `\n${notice}` : "") +
|
|
251
|
+
(value.output === undefined ? "" : `\n${value.output}`);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** A stopped observation says nothing about the target task's final outcome. */
|
|
255
|
+
function waitNotice(value) {
|
|
256
|
+
if (value.waitStatus === "callerCancelled") return "Waiting cancelled by the caller; the target task was not cancelled.";
|
|
257
|
+
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.");
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Read a live snapshot or a cancellable, read-only persistence handle. */
|
|
262
|
+
async function readSessionLog(ctx, sessionId, signal, onCleanup = () => {}) {
|
|
263
|
+
signal?.throwIfAborted();
|
|
146
264
|
const live = ctx.agents.get(sessionId);
|
|
147
265
|
const own = typeof live?.session?.snapshotEvents === "function" ? live.session.snapshotEvents() : undefined;
|
|
148
|
-
let
|
|
149
|
-
if (
|
|
150
|
-
const
|
|
151
|
-
if (
|
|
152
|
-
|
|
153
|
-
|
|
266
|
+
let log = own === undefined ? undefined : { events: own, inheritedEventCount: live.session.inheritedEventCount ?? 0, session: live.session };
|
|
267
|
+
if (log === undefined) {
|
|
268
|
+
const persistence = ctx.get("sessionPersistence");
|
|
269
|
+
if (persistence !== undefined) {
|
|
270
|
+
// rc.2 query.readSession has no cancellation argument. Own a read-only
|
|
271
|
+
// persistence handle instead, never a resumed/writable target agent.
|
|
272
|
+
const reader = await persistence.open(sessionId, "read", { signal });
|
|
273
|
+
let closing;
|
|
274
|
+
const close = () => closing ??= Promise.resolve().then(() => reader.close());
|
|
275
|
+
onCleanup(close);
|
|
276
|
+
try {
|
|
277
|
+
signal?.throwIfAborted();
|
|
278
|
+
log = { ...await reader.read(undefined, undefined, { signal }), inheritedEventCount: reader.inheritedEventCount ?? 0 };
|
|
279
|
+
} finally {
|
|
280
|
+
await close();
|
|
281
|
+
}
|
|
282
|
+
} else {
|
|
283
|
+
const query = ctx.get("sessionQuery");
|
|
284
|
+
if (query === undefined) throw new Error(`this DSH cannot read session ${JSON.stringify(sessionId)}`);
|
|
285
|
+
// Compatibility with hosts exposing only the query service: the outer
|
|
286
|
+
// observation remains bounded, but that service owns its read lifetime.
|
|
287
|
+
log = await query.readSession(sessionId);
|
|
288
|
+
}
|
|
289
|
+
signal?.throwIfAborted();
|
|
154
290
|
}
|
|
291
|
+
return log;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Session-only overview, explicitly not a message result. */
|
|
295
|
+
async function readFinalAnswer(ctx, sessionId, signal, onCleanup) {
|
|
296
|
+
const { events } = await readSessionLog(ctx, sessionId, signal, onCleanup);
|
|
155
297
|
const texts = (content) => (content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
156
298
|
let answer;
|
|
157
299
|
const accumulated = [];
|
|
@@ -176,77 +318,105 @@ function sessionState(ctx, sessionId) {
|
|
|
176
318
|
if (ctx.get("workspaceRegistry")?.archivedSessionIds?.some((id) => String(id) === sessionId) === true) return "archived";
|
|
177
319
|
return ctx.agents.get(sessionId)?.status === "running" ? "running" : "idle";
|
|
178
320
|
}
|
|
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
|
-
}
|
|
321
|
+
/** Pending resumes are shared by plugin instances using the same agent service. */
|
|
322
|
+
const targetResumes = new WeakMap();
|
|
323
|
+
|
|
324
|
+
function checkSendTarget(sessionId, header, callerAgent) {
|
|
325
|
+
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");
|
|
326
|
+
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.`);
|
|
327
|
+
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
328
|
}
|
|
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) {
|
|
329
|
+
|
|
330
|
+
/** Read target metadata without opening a writable session or publishing an agent. */
|
|
331
|
+
async function inspectSendTarget(ctx, sessionId, exec) {
|
|
332
|
+
exec.signal?.throwIfAborted();
|
|
333
|
+
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
334
|
const live = ctx.agents.get(sessionId);
|
|
222
|
-
if (live !== void 0)
|
|
335
|
+
if (live !== void 0) {
|
|
336
|
+
checkSendTarget(sessionId, live.session.header, exec.agent);
|
|
337
|
+
return { agent: live, header: live.session.header };
|
|
338
|
+
}
|
|
223
339
|
const query = ctx.get("sessionQuery");
|
|
224
340
|
if (query === void 0) throw new Error(`session_send cannot open ${JSON.stringify(sessionId)}: this DSH does not offer session lookup`);
|
|
225
341
|
let record;
|
|
226
342
|
try {
|
|
227
|
-
|
|
343
|
+
// listSessions owns and releases its read resources; no handle escapes.
|
|
344
|
+
record = (await query.listSessions(exec.signal)).find((entry) => String(entry.header.id) === sessionId);
|
|
228
345
|
} catch (error) {
|
|
229
346
|
throw new Error(`session_send cannot read ${JSON.stringify(sessionId)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
230
347
|
}
|
|
348
|
+
exec.signal?.throwIfAborted();
|
|
231
349
|
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
|
-
|
|
350
|
+
checkSendTarget(sessionId, record.header, exec.agent);
|
|
351
|
+
return { header: record.header };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Recheck after approval, then serialize resumes so concurrent sends share one agent. */
|
|
355
|
+
async function resolveTargetAgent(ctx, sessionId, exec) {
|
|
356
|
+
const agents = ctx.agents;
|
|
357
|
+
// Cordis creates a fresh traced proxy on each service read. Its exported
|
|
358
|
+
// original symbol gives stable identity; keep using the traced service for
|
|
359
|
+
// method calls so ownership and caller context are still preserved.
|
|
360
|
+
const serviceIdentity = agents[symbols.original] ?? agents;
|
|
361
|
+
let pending = targetResumes.get(serviceIdentity);
|
|
362
|
+
if (pending === void 0) targetResumes.set(serviceIdentity, pending = new Map());
|
|
363
|
+
const previous = pending.get(sessionId);
|
|
364
|
+
const operation = (async () => {
|
|
365
|
+
// A failed/cancelled earlier sender must not invalidate this sender's grant.
|
|
366
|
+
if (previous !== void 0) await previous.catch(() => {});
|
|
367
|
+
const inspected = await inspectSendTarget(ctx, sessionId, exec);
|
|
368
|
+
exec.signal?.throwIfAborted();
|
|
369
|
+
// Another host caller may have published the agent during the metadata read.
|
|
370
|
+
const live = agents.get(sessionId);
|
|
371
|
+
if (live !== void 0) {
|
|
372
|
+
checkSendTarget(sessionId, live.session.header, exec.agent);
|
|
373
|
+
return live;
|
|
374
|
+
}
|
|
375
|
+
const agentPresets = ctx.get("agentPresets");
|
|
376
|
+
const presetId = inspected.header.agentPreset;
|
|
377
|
+
const setup = agentPresets === void 0 || presetId === void 0 ? void 0 : async (agentCtx) => {
|
|
378
|
+
await agentPresets.mount(agentCtx, presetId);
|
|
379
|
+
};
|
|
380
|
+
const resumed = await agents.resume({
|
|
381
|
+
resumeSessionId: sessionId,
|
|
382
|
+
agentOptions: currentSelection(ctx, exec.agent),
|
|
383
|
+
signal: exec.signal,
|
|
384
|
+
...setup === void 0 ? {} : { setup }
|
|
385
|
+
});
|
|
386
|
+
return resumed.agent;
|
|
387
|
+
})();
|
|
388
|
+
pending.set(sessionId, operation);
|
|
389
|
+
const release = () => {
|
|
390
|
+
if (pending.get(sessionId) === operation) pending.delete(sessionId);
|
|
237
391
|
};
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
392
|
+
// Keep the queue slot until the actual operation settles, even if this
|
|
393
|
+
// caller stops waiting. Otherwise a later sender could bypass an active resume.
|
|
394
|
+
void operation.then(release, release);
|
|
395
|
+
if (previous !== void 0 && exec.signal !== void 0) {
|
|
396
|
+
const cancelled = Promise.withResolvers();
|
|
397
|
+
const onAbort = () => cancelled.reject(exec.signal.reason);
|
|
398
|
+
try {
|
|
399
|
+
exec.signal.addEventListener("abort", onAbort, { once: true });
|
|
400
|
+
if (exec.signal.aborted) onAbort();
|
|
401
|
+
await Promise.race([previous.catch(() => {}), cancelled.promise]);
|
|
402
|
+
} finally {
|
|
403
|
+
exec.signal.removeEventListener("abort", onAbort);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return await operation;
|
|
244
407
|
}
|
|
245
408
|
/**
|
|
246
409
|
* Register `session_create` and `session_send`.
|
|
247
410
|
* @param ctx - services of the agent this plugin was loaded for.
|
|
248
411
|
*/
|
|
249
412
|
function apply(ctx) {
|
|
413
|
+
const inSlot = readSlots();
|
|
414
|
+
const sortByActivity = createActivitySorter(ctx, inSlot);
|
|
415
|
+
const listSessions = createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState);
|
|
416
|
+
// Optional capability; the same pure fold also works over a read-only full log.
|
|
417
|
+
if (typeof ctx.inject === "function") ctx.inject(["sessionProjections"], scope => {
|
|
418
|
+
scope.sessionProjections.register(receiptProjection);
|
|
419
|
+
});
|
|
250
420
|
ctx.tools.register(defineTool({
|
|
251
421
|
name: "session_create",
|
|
252
422
|
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 +424,7 @@ function apply(ctx) {
|
|
|
254
424
|
prompt: {
|
|
255
425
|
type: "string",
|
|
256
426
|
required: true,
|
|
257
|
-
description: "The new session's first
|
|
427
|
+
description: "The new session's first task, delivered with plugin provenance. Write it self-contained: the new session cannot see this conversation."
|
|
258
428
|
},
|
|
259
429
|
workspacePath: {
|
|
260
430
|
type: "string",
|
|
@@ -262,11 +432,15 @@ function apply(ctx) {
|
|
|
262
432
|
},
|
|
263
433
|
title: {
|
|
264
434
|
type: "string",
|
|
265
|
-
description: "Optional title.
|
|
435
|
+
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
436
|
},
|
|
267
437
|
wait: {
|
|
268
438
|
type: "boolean",
|
|
269
|
-
description: "Wait for the
|
|
439
|
+
description: "Wait for the first message's recorded turn to end before returning. Defaults to false; bounded by timeoutMs."
|
|
440
|
+
},
|
|
441
|
+
timeoutMs: {
|
|
442
|
+
type: "number",
|
|
443
|
+
description: "Wait budget in milliseconds. Defaults to 60000, at most 300000. Timeout or caller cancellation only ends this wait."
|
|
270
444
|
}
|
|
271
445
|
},
|
|
272
446
|
output: {
|
|
@@ -288,16 +462,26 @@ function apply(ctx) {
|
|
|
288
462
|
},
|
|
289
463
|
workspaceId: { type: "string" },
|
|
290
464
|
workspacePath: { type: "string" },
|
|
291
|
-
title: { type: "string" }
|
|
465
|
+
title: { type: "string" },
|
|
466
|
+
waited: { type: "boolean" },
|
|
467
|
+
completed: { type: "boolean" },
|
|
468
|
+
waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
|
|
469
|
+
elapsedMs: { type: "number" },
|
|
470
|
+
...receiptProperties
|
|
292
471
|
}
|
|
293
472
|
},
|
|
294
|
-
//
|
|
295
|
-
//
|
|
473
|
+
// rc.2 persists this projection on tool/result and exposes it as
|
|
474
|
+
// ToolResultNode.meta. The canonical value alone does not survive replay.
|
|
475
|
+
presentationMeta: (_args, value) => ({
|
|
476
|
+
sessionId: value.sessionId,
|
|
477
|
+
...typeof value.title === "string" ? { title: value.title } : {}
|
|
478
|
+
}),
|
|
479
|
+
// Keep the receipt readable for clients without the session card.
|
|
296
480
|
render: (_args, value) => [{
|
|
297
481
|
type: "text",
|
|
298
|
-
text: value.grouped === true
|
|
482
|
+
text: (value.grouped === true
|
|
299
483
|
? `Created session: ${sessionReference(value.title, value.sessionId)} in workspace ${value.workspacePath}`
|
|
300
|
-
: `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`
|
|
484
|
+
: `Created session: ${sessionReference(value.title, value.sessionId)} (ungrouped)`) + `\n${receiptText(value)}`
|
|
301
485
|
}]
|
|
302
486
|
},
|
|
303
487
|
async execute(args, exec) {
|
|
@@ -325,11 +509,14 @@ function apply(ctx) {
|
|
|
325
509
|
const agentOptions = currentSelection(ctx, exec.agent);
|
|
326
510
|
const agentPresets = ctx.get("agentPresets");
|
|
327
511
|
const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
|
|
512
|
+
exec.signal?.throwIfAborted();
|
|
328
513
|
const sessionId = brandString(`session-${randomUUID()}`);
|
|
329
514
|
let handle;
|
|
330
515
|
let attached = false;
|
|
516
|
+
let sent;
|
|
331
517
|
try {
|
|
332
518
|
handle = await ctx.agents.create({
|
|
519
|
+
signal: exec.signal,
|
|
333
520
|
sessionId,
|
|
334
521
|
agentOptions,
|
|
335
522
|
meta: {
|
|
@@ -341,23 +528,28 @@ function apply(ctx) {
|
|
|
341
528
|
await agentPresets.mount(agentCtx, presetId);
|
|
342
529
|
} }
|
|
343
530
|
});
|
|
531
|
+
exec.signal?.throwIfAborted();
|
|
344
532
|
if (workspace !== void 0) {
|
|
345
533
|
await workspace.attachSession(sessionId);
|
|
346
534
|
attached = true;
|
|
347
535
|
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
536
|
+
exec.signal?.throwIfAborted();
|
|
537
|
+
const title = args.title?.trim() || fallbackSessionTitle(prompt, fallbackTitleWords, fallbackTitleBytes);
|
|
538
|
+
// The public rename operation logs and pins the initial title. It
|
|
539
|
+
// does not change the first message's plugin provenance below.
|
|
540
|
+
ctx.sessionTitle.rename(handle.agent.session, title);
|
|
541
|
+
exec.signal?.throwIfAborted();
|
|
542
|
+
sent = createUserMessage({
|
|
351
543
|
content: [{
|
|
352
544
|
type: "text",
|
|
353
545
|
text: prompt
|
|
354
546
|
}],
|
|
355
547
|
source: {
|
|
356
|
-
kind:
|
|
357
|
-
|
|
548
|
+
kind: name,
|
|
549
|
+
form: "relay"
|
|
358
550
|
}
|
|
359
|
-
})
|
|
360
|
-
|
|
551
|
+
});
|
|
552
|
+
handle.agent.followup(sent);
|
|
361
553
|
} catch (error) {
|
|
362
554
|
if (attached) try {
|
|
363
555
|
await workspace.detachSession(sessionId);
|
|
@@ -367,8 +559,10 @@ function apply(ctx) {
|
|
|
367
559
|
} catch {}
|
|
368
560
|
throw error;
|
|
369
561
|
}
|
|
370
|
-
//
|
|
371
|
-
//
|
|
562
|
+
// Once delivered, the target owns its lifetime. Ending this observation
|
|
563
|
+
// must not detach its workspace or dispose its handle.
|
|
564
|
+
const waited = args.wait === true ? await observeReceipt(ctx, String(sessionId), sent.id, args.timeoutMs, exec.signal) : undefined;
|
|
565
|
+
// Read the accepted title after host normalization (or a manual rename).
|
|
372
566
|
let currentTitle;
|
|
373
567
|
try {
|
|
374
568
|
// The service returns a title snapshot; the text lives on `.title`.
|
|
@@ -376,6 +570,8 @@ function apply(ctx) {
|
|
|
376
570
|
} catch {}
|
|
377
571
|
return {
|
|
378
572
|
sessionId: String(sessionId),
|
|
573
|
+
messageId: sent.id,
|
|
574
|
+
...waited === undefined ? deliveredReceipt(handle.agent, sent.id) : { waited: true, ...waited },
|
|
379
575
|
grouped: workspace !== void 0,
|
|
380
576
|
cwd,
|
|
381
577
|
...currentTitle === void 0 || currentTitle === "" ? {} : { title: String(currentTitle) },
|
|
@@ -406,7 +602,7 @@ function apply(ctx) {
|
|
|
406
602
|
},
|
|
407
603
|
timeoutMs: {
|
|
408
604
|
type: "number",
|
|
409
|
-
description: "How long to
|
|
605
|
+
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
606
|
}
|
|
411
607
|
},
|
|
412
608
|
output: {
|
|
@@ -424,17 +620,15 @@ function apply(ctx) {
|
|
|
424
620
|
},
|
|
425
621
|
waited: { type: "boolean" },
|
|
426
622
|
completed: { type: "boolean" },
|
|
623
|
+
waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
|
|
427
624
|
elapsedMs: { type: "number" },
|
|
428
|
-
|
|
625
|
+
...receiptProperties
|
|
429
626
|
}
|
|
430
627
|
},
|
|
628
|
+
presentationMeta: (_args, value) => ({ sessionId: value.sessionId, messageId: value.messageId }),
|
|
431
629
|
render: (_args, value) => [{
|
|
432
630
|
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`
|
|
631
|
+
text: receiptText(value)
|
|
438
632
|
}]
|
|
439
633
|
},
|
|
440
634
|
async execute(args, exec) {
|
|
@@ -443,54 +637,51 @@ function apply(ctx) {
|
|
|
443
637
|
if (requested === "") throw new Error("session_send needs a session id");
|
|
444
638
|
const message = args.message.trim();
|
|
445
639
|
if (message === "") throw new Error("session_send needs a message");
|
|
446
|
-
|
|
640
|
+
await inspectSendTarget(ctx, requested, exec);
|
|
641
|
+
await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(requested)}: ${message.slice(0, 120)}`);
|
|
642
|
+
const target = await resolveTargetAgent(ctx, requested, exec);
|
|
643
|
+
exec.signal?.throwIfAborted();
|
|
447
644
|
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)}`);
|
|
645
|
+
if (targetId !== requested) throw new Error("session_send resolved a different target; no message was sent");
|
|
646
|
+
checkSendTarget(targetId, target.session.header, exec.agent);
|
|
454
647
|
const sent = createUserMessage({
|
|
455
648
|
content: [{
|
|
456
649
|
type: "text",
|
|
457
650
|
text: message
|
|
458
651
|
}],
|
|
459
652
|
source: {
|
|
460
|
-
kind:
|
|
461
|
-
|
|
653
|
+
kind: name,
|
|
654
|
+
form: "relay"
|
|
462
655
|
}
|
|
463
656
|
});
|
|
464
657
|
target.followup(sent);
|
|
465
658
|
if (args.wait !== true) return {
|
|
466
659
|
sessionId: targetId,
|
|
660
|
+
messageId: sent.id,
|
|
661
|
+
...deliveredReceipt(target, sent.id),
|
|
467
662
|
cwd: String(target.session.header.cwd ?? "")
|
|
468
663
|
};
|
|
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);
|
|
664
|
+
const result = await observeReceipt(ctx, targetId, sent.id, args.timeoutMs, exec.signal);
|
|
477
665
|
return {
|
|
478
666
|
sessionId: targetId,
|
|
667
|
+
messageId: sent.id,
|
|
479
668
|
cwd: String(target.session.header.cwd ?? ""),
|
|
480
669
|
waited: true,
|
|
481
|
-
|
|
482
|
-
elapsedMs: Date.now() - startedAt,
|
|
483
|
-
...answer === void 0 ? {} : { output: answer }
|
|
670
|
+
...result
|
|
484
671
|
};
|
|
485
672
|
}
|
|
486
673
|
}));
|
|
487
674
|
ctx.tools.register(defineTool({
|
|
488
675
|
name: "list_sessions",
|
|
489
|
-
description: "List the sessions the person can see,
|
|
676
|
+
description: "List the sessions the person can see, most recent conversation activity first, with each id and current state (working, waiting, or put away). New input, model output/attempts, execution starts and non-recovery turn endings count. Bare step/tool completion, title-only changes and recovery do not advance activity. Sessions without conversation activity use creation time; ties keep the host's order. Use it before session_send when the target is described by name rather than by id.",
|
|
490
677
|
parameters: {
|
|
678
|
+
titleQuery: { type: "string", description: "Literal title substring, NFC/whitespace normalized and case-insensitive; at most 1024 UTF-8 bytes. Applied before limit. A failed title read fails the complete query." },
|
|
679
|
+
workspaceId: { type: "string", description: "Existing workspace ID (at most 256 UTF-8 bytes); mutually exclusive with workspacePath. Uses actual workspace membership." },
|
|
680
|
+
workspacePath: { type: "string", description: "Absolute path of an existing registered workspace (at most 4096 UTF-8 bytes); mutually exclusive with workspaceId." },
|
|
681
|
+
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." },
|
|
491
682
|
limit: {
|
|
492
683
|
type: "number",
|
|
493
|
-
description: "How many sessions to list, most recently active first. Defaults to 20."
|
|
684
|
+
description: "How many sessions to list, most recently active first. Defaults to 20, capped at 100. May change between pages."
|
|
494
685
|
}
|
|
495
686
|
},
|
|
496
687
|
output: {
|
|
@@ -522,6 +713,13 @@ function apply(ctx) {
|
|
|
522
713
|
}
|
|
523
714
|
}
|
|
524
715
|
},
|
|
716
|
+
matchedTotal: { type: "number", required: true, description: "Ordinary sessions matching the initial successful scan, before limit; frozen across pages." },
|
|
717
|
+
nextCursor: { type: "string" },
|
|
718
|
+
resultSetCreatedAt: { type: "number", description: "Result set creation time in Unix milliseconds; not an atomic database snapshot." },
|
|
719
|
+
resultSetExpiresAt: { type: "number", description: "Fixed expiration time in Unix milliseconds." },
|
|
720
|
+
paginationUnavailable: { type: "string" },
|
|
721
|
+
workspaceId: { type: "string" },
|
|
722
|
+
workspacePath: { type: "string" },
|
|
525
723
|
total: {
|
|
526
724
|
type: "number",
|
|
527
725
|
required: true
|
|
@@ -530,8 +728,8 @@ function apply(ctx) {
|
|
|
530
728
|
},
|
|
531
729
|
render: (_args, value) => [{
|
|
532
730
|
type: "text",
|
|
533
|
-
text: value.
|
|
534
|
-
? "No
|
|
731
|
+
text: value.sessions.length === 0
|
|
732
|
+
? "No matching sessions."
|
|
535
733
|
: [
|
|
536
734
|
value.sessions.map((entry) => [
|
|
537
735
|
sessionReference(entry.title, entry.sessionId),
|
|
@@ -541,53 +739,27 @@ function apply(ctx) {
|
|
|
541
739
|
entry.state === "archived" ? "(put away)" : undefined,
|
|
542
740
|
entry.cwd
|
|
543
741
|
].filter((part) => part !== undefined).join(" · ")).join("\n"),
|
|
544
|
-
value.sessions.some((entry) => entry.state === "archived") ? "Sessions marked (put away) are archived: they are hidden from the sidebar but still listed here." : undefined
|
|
742
|
+
value.sessions.some((entry) => entry.state === "archived") ? "Sessions marked (put away) are archived: they are hidden from the sidebar but still listed here." : undefined,
|
|
743
|
+
value.nextCursor ? `More matching sessions: use nextCursor ${value.nextCursor} before ${new Date(value.resultSetExpiresAt).toISOString()}.` : undefined,
|
|
744
|
+
value.paginationUnavailable
|
|
545
745
|
].filter((part) => part !== undefined).join("\n")
|
|
546
746
|
}]
|
|
547
747
|
},
|
|
548
|
-
|
|
549
|
-
const query = ctx.get("sessionQuery");
|
|
550
|
-
if (query === void 0) throw new Error("list_sessions needs session lookup, which this DSH does not offer");
|
|
551
|
-
const requested = args.limit === void 0 ? 20 : Math.trunc(args.limit);
|
|
552
|
-
const limit = requested < 1 ? 1 : requested > 100 ? 100 : requested;
|
|
553
|
-
const self = exec.agent === void 0 ? undefined : String(exec.agent.id);
|
|
554
|
-
const records = await query.listSessions();
|
|
555
|
-
const listed = [];
|
|
556
|
-
let total = 0;
|
|
557
|
-
for (const record of records) {
|
|
558
|
-
const header = record.header;
|
|
559
|
-
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
|
-
let title;
|
|
566
|
-
try {
|
|
567
|
-
// Title reads return a snapshot, not a string: the text lives on
|
|
568
|
-
// `.title`, exactly like the title service the create path uses.
|
|
569
|
-
title = (await query.readTitle(sessionId))?.title;
|
|
570
|
-
} catch {}
|
|
571
|
-
listed.push({
|
|
572
|
-
sessionId,
|
|
573
|
-
...title === void 0 || title === "" ? {} : { title: String(title) },
|
|
574
|
-
...header.cwd === void 0 ? {} : { cwd: String(header.cwd) },
|
|
575
|
-
state: sessionState(ctx, sessionId),
|
|
576
|
-
...sessionId === self ? { current: true } : {}
|
|
577
|
-
});
|
|
578
|
-
}
|
|
579
|
-
return { sessions: listed, total };
|
|
580
|
-
}
|
|
748
|
+
execute: listSessions
|
|
581
749
|
}));
|
|
582
750
|
ctx.tools.register(defineTool({
|
|
583
751
|
name: "session_wait",
|
|
584
|
-
description: "
|
|
752
|
+
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
753
|
parameters: {
|
|
586
754
|
sessionId: {
|
|
587
755
|
type: "string",
|
|
588
756
|
required: true,
|
|
589
757
|
description: "Target Session id, for example \"session-2330bd36-fe62-4621-8d42-c7e04566f447\"."
|
|
590
758
|
},
|
|
759
|
+
messageId: {
|
|
760
|
+
type: "string",
|
|
761
|
+
description: "The exact messageId returned with sessionId by session_send or session_create, including after timeout. Omit only for a session overview."
|
|
762
|
+
},
|
|
591
763
|
timeoutMs: {
|
|
592
764
|
type: "number",
|
|
593
765
|
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 +782,18 @@ function apply(ctx) {
|
|
|
610
782
|
type: "boolean",
|
|
611
783
|
required: true
|
|
612
784
|
},
|
|
785
|
+
waitStatus: { type: "string", enum: ["completed", "timedOut", "callerCancelled"] },
|
|
613
786
|
elapsedMs: { type: "number" },
|
|
614
|
-
|
|
787
|
+
scope: { type: "string", enum: ["message", "sessionOverview"] },
|
|
788
|
+
...receiptProperties
|
|
615
789
|
}
|
|
616
790
|
},
|
|
617
791
|
render: (_args, value) => [{
|
|
618
792
|
type: "text",
|
|
619
|
-
text: value.
|
|
620
|
-
|
|
621
|
-
|
|
793
|
+
text: value.scope === "message" ? receiptText(value) :
|
|
794
|
+
`Session overview for ${value.sessionId} (not a message result): ` +
|
|
795
|
+
(waitNotice(value) ?? (value.running ? "running" : "idle")) +
|
|
796
|
+
(value.output === undefined ? "" : `\nLatest session answer, not attributed to any receipt:\n${value.output}`)
|
|
622
797
|
}]
|
|
623
798
|
},
|
|
624
799
|
async execute(args, exec) {
|
|
@@ -626,36 +801,33 @@ function apply(ctx) {
|
|
|
626
801
|
if (requested === "") throw new Error("session_wait needs a session id");
|
|
627
802
|
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
803
|
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);
|
|
804
|
+
if (args.messageId !== undefined) {
|
|
805
|
+
const messageId = args.messageId.trim();
|
|
806
|
+
if (messageId === "") throw new Error("session_wait needs a non-empty messageId, or omit it for a session overview");
|
|
807
|
+
const result = await observeReceipt(ctx, requested, messageId, args.timeoutMs, exec.signal);
|
|
637
808
|
return {
|
|
638
|
-
sessionId: requested,
|
|
639
|
-
|
|
640
|
-
completed: true,
|
|
641
|
-
elapsedMs: 0,
|
|
642
|
-
...answer === void 0 ? {} : { output: answer }
|
|
809
|
+
sessionId: requested, messageId, scope: "message", running: ctx.agents.get(requested)?.status === "running",
|
|
810
|
+
...result
|
|
643
811
|
};
|
|
644
812
|
}
|
|
645
|
-
|
|
646
|
-
const
|
|
647
|
-
target
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
813
|
+
|
|
814
|
+
const result = await observeWait(args.timeoutMs, exec.signal, async (signal, onCleanup) => {
|
|
815
|
+
if (target === undefined) {
|
|
816
|
+
const query = ctx.get("sessionQuery");
|
|
817
|
+
if (query === undefined) throw new Error(`session_wait cannot check ${JSON.stringify(requested)}: this DSH does not offer session lookup`);
|
|
818
|
+
const known = (await query.listSessions(signal)).some(entry => String(entry.header.id) === requested);
|
|
819
|
+
signal.throwIfAborted();
|
|
820
|
+
if (!known) throw new Error(`session_wait cannot find session ${JSON.stringify(requested)}: no open or saved session has that id`);
|
|
821
|
+
} else await target.whenIdle();
|
|
822
|
+
signal.throwIfAborted();
|
|
823
|
+
const answer = await readFinalAnswer(ctx, requested, signal, onCleanup);
|
|
824
|
+
return answer === undefined ? {} : { output: answer };
|
|
825
|
+
});
|
|
653
826
|
return {
|
|
654
827
|
sessionId: requested,
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
...answer === void 0 ? {} : { output: answer }
|
|
828
|
+
scope: "sessionOverview",
|
|
829
|
+
running: target?.status === "running",
|
|
830
|
+
...result
|
|
659
831
|
};
|
|
660
832
|
}
|
|
661
833
|
}));
|