@ryuu-64/dsh-session-tools 0.6.0 → 0.8.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 +49 -170
- package/lib/client.js +397 -2
- package/lib/communication-permissions.js +101 -0
- package/lib/communication-remote.js +64 -0
- package/lib/index.js +96 -51
- package/lib/session-activity.js +26 -14
- package/lib/session-discovery.js +213 -0
- package/package.json +99 -76
package/lib/index.js
CHANGED
|
@@ -8,9 +8,12 @@ import { brandString } from "@deepseek-ai/dsh-brand";
|
|
|
8
8
|
import { symbols } from "@deepseek-ai/cordis";
|
|
9
9
|
import { fallbackSessionTitle } from "@deepseek-ai/dsh-session-title";
|
|
10
10
|
import { receiptProjection, receiptProjectionKey, foldReceipts, messageReceipt } from "./message-receipts.js";
|
|
11
|
-
import { createActivitySorter } from "./session-activity.js";
|
|
11
|
+
import { createActivitySorter, readSlots } from "./session-activity.js";
|
|
12
|
+
import { createSessionDiscovery } from "./session-discovery.js";
|
|
13
|
+
import { communicationPermissions, trustedSource, unknownCommunication, communicationStatusSchema, communicationStatusText } from "./communication-permissions.js";
|
|
14
|
+
import { CommunicationRemote } from "./communication-remote.js";
|
|
12
15
|
|
|
13
|
-
/** Stable Loader identity. */
|
|
16
|
+
/** Stable Loader identity and producer-owned message source (V3 and V4). */
|
|
14
17
|
const name = "tool-session";
|
|
15
18
|
/** Nothing to configure. */
|
|
16
19
|
const Config = z.object({});
|
|
@@ -24,7 +27,8 @@ const inject = [
|
|
|
24
27
|
"agents",
|
|
25
28
|
"sessionTitle",
|
|
26
29
|
"workspaceRegistry",
|
|
27
|
-
"agentDefaultModel"
|
|
30
|
+
"agentDefaultModel",
|
|
31
|
+
"storageDomain"
|
|
28
32
|
];
|
|
29
33
|
/** List the existing workspaces, so a rejected path tells the caller what to use instead. */
|
|
30
34
|
function workspaceCatalogue(registry) {
|
|
@@ -241,11 +245,18 @@ const receiptProperties = {
|
|
|
241
245
|
output: { type: "string" }
|
|
242
246
|
};
|
|
243
247
|
|
|
248
|
+
function receiptMeta(value) {
|
|
249
|
+
return Object.fromEntries(["sessionId", "messageId", "messageStatus", "waitStatus", "turn", "turnEndKind", "attributionNote"].filter(key => value[key] !== undefined).map(key => [key, value[key]]));
|
|
250
|
+
}
|
|
251
|
+
const statusLabels = {
|
|
252
|
+
queued: "已排队", delivered: "已交给目标", turnCompleted: "目标本轮结束(不等于任务成功)",
|
|
253
|
+
discarded: "取消", cancelled: "取消", interrupted: "中断", failed: "失败",
|
|
254
|
+
incomplete: "未完整结束", blocked: "未完整结束", unknown: "暂无法确认",
|
|
255
|
+
};
|
|
244
256
|
function receiptText(value) {
|
|
245
257
|
const receipt = `Receipt: sessionId=${value.sessionId}, messageId=${value.messageId}`;
|
|
246
258
|
const notice = waitNotice(value);
|
|
247
|
-
return `${
|
|
248
|
-
(value.messageStatus === "turnCompleted" ? " The recorded turn completed; this does not verify the business task succeeded." : "") +
|
|
259
|
+
return `${statusLabels[value.messageStatus] ?? "暂无法确认"}\n${receipt}` +
|
|
249
260
|
(value.attributionNote ? `\n${value.attributionNote}` : "") + (notice ? `\n${notice}` : "") +
|
|
250
261
|
(value.output === undefined ? "" : `\n${value.output}`);
|
|
251
262
|
}
|
|
@@ -409,7 +420,45 @@ async function resolveTargetAgent(ctx, sessionId, exec) {
|
|
|
409
420
|
* @param ctx - services of the agent this plugin was loaded for.
|
|
410
421
|
*/
|
|
411
422
|
function apply(ctx) {
|
|
412
|
-
const
|
|
423
|
+
const permissions = communicationPermissions(ctx);
|
|
424
|
+
ctx.inject(["typert", "connection"], scope => { scope.plugin(CommunicationRemote); });
|
|
425
|
+
const inSlot = readSlots();
|
|
426
|
+
const sortByActivity = createActivitySorter(ctx, inSlot);
|
|
427
|
+
const listSessions = createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState);
|
|
428
|
+
ctx.tools.register(defineTool({
|
|
429
|
+
name: "session_communication_status",
|
|
430
|
+
description: "Read whether this session's send switch and a visible ordinary target's receive switch currently allow communication. Optional: use when you only want to check a known target, including whether it has reopened. This does not send, wake, subscribe, grant approval, or guarantee later delivery. Normal sends need no separate preflight; session_send always rechecks.",
|
|
431
|
+
parameters: { sessionId: { type: "string", required: true, description: "Target ordinary session ID." } },
|
|
432
|
+
output: {
|
|
433
|
+
schema: { type: "object", additionalProperties: false, properties: {
|
|
434
|
+
sessionId: { type: "string", required: true },
|
|
435
|
+
communication: { ...communicationStatusSchema, required: true },
|
|
436
|
+
} },
|
|
437
|
+
render: (_args, value) => [{ type: "text", text: `${communicationStatusText(value.communication)}。仅为当前开关状态,不代表已投递,也不替代审批和其他发送限制;发送时仍会重检。` }],
|
|
438
|
+
},
|
|
439
|
+
async execute(args, exec) {
|
|
440
|
+
const requested = args.sessionId.trim();
|
|
441
|
+
let communication = unknownCommunication();
|
|
442
|
+
try {
|
|
443
|
+
const sourceId = trustedSource(exec);
|
|
444
|
+
if (!requested || requested.length > 1024) return { sessionId: requested, communication };
|
|
445
|
+
// Resolve visibility before reading permissions: arbitrary IDs must
|
|
446
|
+
// never reveal defaults or records outside the host's catalog.
|
|
447
|
+
const query = ctx.get("sessionQuery");
|
|
448
|
+
if (!query) return { sessionId: requested, communication };
|
|
449
|
+
const record = (await query.listSessions(exec.signal)).find(row =>
|
|
450
|
+
String(row.header.id) === requested && (row.header.delegationDepth ?? 0) <= 0 && row.header.origin !== "subagent");
|
|
451
|
+
exec.signal?.throwIfAborted();
|
|
452
|
+
if (!record) return { sessionId: requested, communication };
|
|
453
|
+
// Read switch state only. cwd/self and other delivery restrictions
|
|
454
|
+
// remain session_send concerns, just as for list_sessions rows.
|
|
455
|
+
[communication] = await permissions.statuses(sourceId, [requested]);
|
|
456
|
+
} catch {
|
|
457
|
+
exec.signal?.throwIfAborted();
|
|
458
|
+
}
|
|
459
|
+
return { sessionId: requested, communication };
|
|
460
|
+
},
|
|
461
|
+
}));
|
|
413
462
|
// Optional capability; the same pure fold also works over a read-only full log.
|
|
414
463
|
if (typeof ctx.inject === "function") ctx.inject(["sessionProjections"], scope => {
|
|
415
464
|
scope.sessionProjections.register(receiptProjection);
|
|
@@ -471,6 +520,7 @@ function apply(ctx) {
|
|
|
471
520
|
// ToolResultNode.meta. The canonical value alone does not survive replay.
|
|
472
521
|
presentationMeta: (_args, value) => ({
|
|
473
522
|
sessionId: value.sessionId,
|
|
523
|
+
...receiptMeta(value),
|
|
474
524
|
...typeof value.title === "string" ? { title: value.title } : {}
|
|
475
525
|
}),
|
|
476
526
|
// Keep the receipt readable for clients without the session card.
|
|
@@ -483,6 +533,8 @@ function apply(ctx) {
|
|
|
483
533
|
},
|
|
484
534
|
async execute(args, exec) {
|
|
485
535
|
if (exec.agent === void 0) throw new Error("session_create must run inside a session");
|
|
536
|
+
const sourceId = trustedSource(exec);
|
|
537
|
+
await permissions.check(sourceId);
|
|
486
538
|
const prompt = args.prompt.trim();
|
|
487
539
|
if (prompt === "") throw new Error("session_create needs a prompt: it becomes the new session's first user message");
|
|
488
540
|
let workspace;
|
|
@@ -502,7 +554,9 @@ function apply(ctx) {
|
|
|
502
554
|
// Ask before creating anything: a session that appears in the person's
|
|
503
555
|
// list without them knowing about it is the whole risk of this tool.
|
|
504
556
|
const where = workspace === void 0 ? "ungrouped" : `in workspace ${JSON.stringify(workspace.path)}`;
|
|
557
|
+
await permissions.check(sourceId);
|
|
505
558
|
await requireApproval(ctx, exec, `create a new session ${where}, starting with: ${prompt.slice(0, 120)}`);
|
|
559
|
+
await permissions.check(sourceId);
|
|
506
560
|
const agentOptions = currentSelection(ctx, exec.agent);
|
|
507
561
|
const agentPresets = ctx.get("agentPresets");
|
|
508
562
|
const presetId = await resolvePreset(ctx, exec.agent, agentPresets);
|
|
@@ -542,11 +596,11 @@ function apply(ctx) {
|
|
|
542
596
|
text: prompt
|
|
543
597
|
}],
|
|
544
598
|
source: {
|
|
545
|
-
kind:
|
|
546
|
-
|
|
599
|
+
kind: name,
|
|
600
|
+
form: "relay"
|
|
547
601
|
}
|
|
548
602
|
});
|
|
549
|
-
handle.agent.followup(sent);
|
|
603
|
+
await permissions.admit(sourceId, String(sessionId), exec, () => handle.agent.followup(sent));
|
|
550
604
|
} catch (error) {
|
|
551
605
|
if (attached) try {
|
|
552
606
|
await workspace.detachSession(sessionId);
|
|
@@ -622,7 +676,7 @@ function apply(ctx) {
|
|
|
622
676
|
...receiptProperties
|
|
623
677
|
}
|
|
624
678
|
},
|
|
625
|
-
presentationMeta: (_args, value) => (
|
|
679
|
+
presentationMeta: (_args, value) => receiptMeta(value),
|
|
626
680
|
render: (_args, value) => [{
|
|
627
681
|
type: "text",
|
|
628
682
|
text: receiptText(value)
|
|
@@ -630,12 +684,16 @@ function apply(ctx) {
|
|
|
630
684
|
},
|
|
631
685
|
async execute(args, exec) {
|
|
632
686
|
if (exec.agent === void 0) throw new Error("session_send must run inside a session");
|
|
687
|
+
const sourceId = trustedSource(exec);
|
|
633
688
|
const requested = args.sessionId.trim();
|
|
634
689
|
if (requested === "") throw new Error("session_send needs a session id");
|
|
635
690
|
const message = args.message.trim();
|
|
636
691
|
if (message === "") throw new Error("session_send needs a message");
|
|
692
|
+
await permissions.check(sourceId, requested);
|
|
637
693
|
await inspectSendTarget(ctx, requested, exec);
|
|
694
|
+
await permissions.check(sourceId, requested);
|
|
638
695
|
await requireApproval(ctx, exec, `send a message into session ${JSON.stringify(requested)}: ${message.slice(0, 120)}`);
|
|
696
|
+
await permissions.check(sourceId, requested);
|
|
639
697
|
const target = await resolveTargetAgent(ctx, requested, exec);
|
|
640
698
|
exec.signal?.throwIfAborted();
|
|
641
699
|
const targetId = String(target.id);
|
|
@@ -647,11 +705,11 @@ function apply(ctx) {
|
|
|
647
705
|
text: message
|
|
648
706
|
}],
|
|
649
707
|
source: {
|
|
650
|
-
kind:
|
|
651
|
-
|
|
708
|
+
kind: name,
|
|
709
|
+
form: "relay"
|
|
652
710
|
}
|
|
653
711
|
});
|
|
654
|
-
target.followup(sent);
|
|
712
|
+
await permissions.admit(sourceId, targetId, exec, () => target.followup(sent));
|
|
655
713
|
if (args.wait !== true) return {
|
|
656
714
|
sessionId: targetId,
|
|
657
715
|
messageId: sent.id,
|
|
@@ -670,11 +728,15 @@ function apply(ctx) {
|
|
|
670
728
|
}));
|
|
671
729
|
ctx.tools.register(defineTool({
|
|
672
730
|
name: "list_sessions",
|
|
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.",
|
|
731
|
+
description: "List the sessions the person can see, most recent conversation activity first, with each id and current state (working, waiting, or put away). New input, model output/attempts, execution starts and non-recovery turn endings count. Bare step/tool completion, title-only changes and recovery do not advance activity. Sessions without conversation activity use creation time; ties keep the host's order. Use it before session_send when the target is described by name rather than by id. Each row includes a fresh caller-to-target communication-switch snapshot, not approval or a delivery guarantee; never cache it as permission to send.",
|
|
674
732
|
parameters: {
|
|
733
|
+
titleQuery: { type: "string", description: "Literal title substring, NFC/whitespace normalized and case-insensitive; at most 1024 UTF-8 bytes. Applied before limit. A failed title read fails the complete query." },
|
|
734
|
+
workspaceId: { type: "string", description: "Existing workspace ID (at most 256 UTF-8 bytes); mutually exclusive with workspacePath. Uses actual workspace membership." },
|
|
735
|
+
workspacePath: { type: "string", description: "Absolute path of an existing registered workspace (at most 4096 UTF-8 bytes); mutually exclusive with workspaceId." },
|
|
736
|
+
cursor: { type: "string", description: "Opaque nextCursor from this caller's previous page. Omit filters to inherit them; explicit filters must match. Expires after 5 minutes; no cursor starts a fresh query." },
|
|
675
737
|
limit: {
|
|
676
738
|
type: "number",
|
|
677
|
-
description: "How many sessions to list, most recently active first. Defaults to 20."
|
|
739
|
+
description: "How many sessions to list, most recently active first. Defaults to 20, capped at 100. May change between pages."
|
|
678
740
|
}
|
|
679
741
|
},
|
|
680
742
|
output: {
|
|
@@ -702,10 +764,18 @@ function apply(ctx) {
|
|
|
702
764
|
description: "What the session is doing right now: running (working on a turn), idle (open or saved, not working), archived (put away from the sidebar)."
|
|
703
765
|
},
|
|
704
766
|
current: { type: "boolean" },
|
|
705
|
-
subagent: { type: "boolean" }
|
|
767
|
+
subagent: { type: "boolean" },
|
|
768
|
+
communication: { ...communicationStatusSchema, required: true }
|
|
706
769
|
}
|
|
707
770
|
}
|
|
708
771
|
},
|
|
772
|
+
matchedTotal: { type: "number", required: true, description: "Ordinary sessions matching the initial successful scan, before limit; frozen across pages." },
|
|
773
|
+
nextCursor: { type: "string" },
|
|
774
|
+
resultSetCreatedAt: { type: "number", description: "Result set creation time in Unix milliseconds; not an atomic database snapshot." },
|
|
775
|
+
resultSetExpiresAt: { type: "number", description: "Fixed expiration time in Unix milliseconds." },
|
|
776
|
+
paginationUnavailable: { type: "string" },
|
|
777
|
+
workspaceId: { type: "string" },
|
|
778
|
+
workspacePath: { type: "string" },
|
|
709
779
|
total: {
|
|
710
780
|
type: "number",
|
|
711
781
|
required: true
|
|
@@ -714,8 +784,8 @@ function apply(ctx) {
|
|
|
714
784
|
},
|
|
715
785
|
render: (_args, value) => [{
|
|
716
786
|
type: "text",
|
|
717
|
-
text: value.
|
|
718
|
-
? "No
|
|
787
|
+
text: value.sessions.length === 0
|
|
788
|
+
? "No matching sessions."
|
|
719
789
|
: [
|
|
720
790
|
value.sessions.map((entry) => [
|
|
721
791
|
sessionReference(entry.title, entry.sessionId),
|
|
@@ -723,43 +793,17 @@ function apply(ctx) {
|
|
|
723
793
|
entry.subagent === true ? "(subagent)" : undefined,
|
|
724
794
|
entry.state === "running" ? "(working now)" : undefined,
|
|
725
795
|
entry.state === "archived" ? "(put away)" : undefined,
|
|
726
|
-
entry.cwd
|
|
796
|
+
entry.cwd,
|
|
797
|
+
communicationStatusText(entry.communication)
|
|
727
798
|
].filter((part) => part !== undefined).join(" · ")).join("\n"),
|
|
728
|
-
|
|
799
|
+
"通信状态仅为当前开关快照,不替代审批或其他发送限制;发送时仍重检。",
|
|
800
|
+
value.sessions.some((entry) => entry.state === "archived") ? "Sessions marked (put away) are archived: they are hidden from the sidebar but still listed here." : undefined,
|
|
801
|
+
value.nextCursor ? `More matching sessions: use nextCursor ${value.nextCursor} before ${new Date(value.resultSetExpiresAt).toISOString()}.` : undefined,
|
|
802
|
+
value.paginationUnavailable
|
|
729
803
|
].filter((part) => part !== undefined).join("\n")
|
|
730
804
|
}]
|
|
731
805
|
},
|
|
732
|
-
|
|
733
|
-
const query = ctx.get("sessionQuery");
|
|
734
|
-
if (query === void 0) throw new Error("list_sessions needs session lookup, which this DSH does not offer");
|
|
735
|
-
const requested = args.limit === void 0 ? 20 : Math.trunc(args.limit);
|
|
736
|
-
const limit = requested < 1 ? 1 : requested > 100 ? 100 : requested;
|
|
737
|
-
const self = exec.agent === void 0 ? undefined : String(exec.agent.id);
|
|
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);
|
|
741
|
-
const listed = [];
|
|
742
|
-
for (const record of ordered.slice(0, limit)) {
|
|
743
|
-
exec.signal?.throwIfAborted();
|
|
744
|
-
const header = record.header;
|
|
745
|
-
const sessionId = String(header.id);
|
|
746
|
-
let title;
|
|
747
|
-
try {
|
|
748
|
-
// Title reads return a snapshot, not a string: the text lives on
|
|
749
|
-
// `.title`, exactly like the title service the create path uses.
|
|
750
|
-
title = (await query.readTitle(sessionId, exec.signal))?.title;
|
|
751
|
-
} catch {}
|
|
752
|
-
exec.signal?.throwIfAborted();
|
|
753
|
-
listed.push({
|
|
754
|
-
sessionId,
|
|
755
|
-
...title === void 0 || title === "" ? {} : { title: String(title) },
|
|
756
|
-
...header.cwd === void 0 ? {} : { cwd: String(header.cwd) },
|
|
757
|
-
state: sessionState(ctx, sessionId),
|
|
758
|
-
...sessionId === self ? { current: true } : {}
|
|
759
|
-
});
|
|
760
|
-
}
|
|
761
|
-
return { sessions: listed, total: records.length };
|
|
762
|
-
}
|
|
806
|
+
execute: listSessions
|
|
763
807
|
}));
|
|
764
808
|
ctx.tools.register(defineTool({
|
|
765
809
|
name: "session_wait",
|
|
@@ -802,6 +846,7 @@ function apply(ctx) {
|
|
|
802
846
|
...receiptProperties
|
|
803
847
|
}
|
|
804
848
|
},
|
|
849
|
+
presentationMeta: (_args, value) => ({ ...receiptMeta(value), scope: value.scope }),
|
|
805
850
|
render: (_args, value) => [{
|
|
806
851
|
type: "text",
|
|
807
852
|
text: value.scope === "message" ? receiptText(value) :
|
package/lib/session-activity.js
CHANGED
|
@@ -21,30 +21,38 @@ export function conversationActivity(events, createdAt, inheritedEventCount = 0)
|
|
|
21
21
|
return latest ?? (Number.isFinite(createdAt) ? createdAt : 0);
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
/** Four
|
|
25
|
-
function readSlots() {
|
|
24
|
+
/** Four shared permits. A title batch takes all four atomically, never partial permits. */
|
|
25
|
+
export function readSlots() {
|
|
26
26
|
let active = 0;
|
|
27
27
|
const waiting = [];
|
|
28
|
-
|
|
28
|
+
const pump = () => {
|
|
29
|
+
while (waiting.length && active + waiting[0].weight <= 4) {
|
|
30
|
+
const entry = waiting.shift();
|
|
31
|
+
active += entry.weight;
|
|
32
|
+
entry.start();
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
return async (read, signal, weight = 1) => {
|
|
36
|
+
if (!Number.isInteger(weight) || weight < 1 || weight > 4) throw new Error("invalid read permit weight");
|
|
29
37
|
signal?.throwIfAborted();
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const entry = { resolve: () => { signal?.removeEventListener("abort", abort); resolve(); } };
|
|
38
|
+
await new Promise((resolve, reject) => {
|
|
39
|
+
const entry = { weight, start: () => { signal?.removeEventListener("abort", abort); resolve(); } };
|
|
33
40
|
const abort = () => {
|
|
34
41
|
const index = waiting.indexOf(entry);
|
|
35
42
|
if (index >= 0) waiting.splice(index, 1);
|
|
36
43
|
reject(signal.reason);
|
|
44
|
+
pump();
|
|
37
45
|
};
|
|
38
46
|
waiting.push(entry);
|
|
39
47
|
signal?.addEventListener("abort", abort, { once: true });
|
|
48
|
+
pump();
|
|
40
49
|
});
|
|
41
50
|
try {
|
|
42
51
|
signal?.throwIfAborted();
|
|
43
52
|
return await read();
|
|
44
53
|
} finally {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
else active--;
|
|
54
|
+
active -= weight;
|
|
55
|
+
pump();
|
|
48
56
|
}
|
|
49
57
|
};
|
|
50
58
|
}
|
|
@@ -52,10 +60,9 @@ function readSlots() {
|
|
|
52
60
|
const identity = service => service?.[symbols.original] ?? service;
|
|
53
61
|
|
|
54
62
|
/** Cache only the derived number, never a log, a read handle, or an Agent. */
|
|
55
|
-
export function createActivitySorter(ctx) {
|
|
63
|
+
export function createActivitySorter(ctx, inSlot = readSlots()) {
|
|
56
64
|
const cache = new Map();
|
|
57
65
|
const liveCache = new WeakMap();
|
|
58
|
-
const inSlot = readSlots();
|
|
59
66
|
async function activity(record, signal) {
|
|
60
67
|
const id = String(record.header.id);
|
|
61
68
|
const live = ctx.get("sessions")?.get(id) ?? ctx.agents.get(id)?.session;
|
|
@@ -94,10 +101,9 @@ export function createActivitySorter(ctx) {
|
|
|
94
101
|
signal?.throwIfAborted();
|
|
95
102
|
return conversationActivity(log.events, record.header.createdAt, log.inheritedEventCount);
|
|
96
103
|
}
|
|
97
|
-
|
|
104
|
+
const sort = async (records, signal, directory = records) => {
|
|
98
105
|
signal?.throwIfAborted();
|
|
99
|
-
|
|
100
|
-
for (const id of cache.keys()) if (!ids.has(id)) cache.delete(id);
|
|
106
|
+
sort.prune(directory);
|
|
101
107
|
// Wait for every observation to close, including after an error/abort.
|
|
102
108
|
const ordered = [];
|
|
103
109
|
let next = 0;
|
|
@@ -120,4 +126,10 @@ export function createActivitySorter(ctx) {
|
|
|
120
126
|
.sort((a, b) => b.time - a.time || a.index - b.index)
|
|
121
127
|
.map(({ record }) => record);
|
|
122
128
|
};
|
|
129
|
+
// A filtered workspace is not the directory: never prune other workspaces.
|
|
130
|
+
sort.prune = (records) => {
|
|
131
|
+
const ids = new Set(records.map(record => String(record.header.id)));
|
|
132
|
+
for (const id of cache.keys()) if (!ids.has(id)) cache.delete(id);
|
|
133
|
+
};
|
|
134
|
+
return sort;
|
|
123
135
|
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
3
|
+
import { symbols } from "@deepseek-ai/cordis";
|
|
4
|
+
import { communicationPermissions, trustedSource, unknownCommunication } from "./communication-permissions.js";
|
|
5
|
+
|
|
6
|
+
// Resource guards, not measured throughput promises. No event/log/Agent is retained.
|
|
7
|
+
const TTL = 5 * 60_000;
|
|
8
|
+
const MAX_SETS = 16;
|
|
9
|
+
const MAX_SET_IDS = 10_000;
|
|
10
|
+
const MAX_IDS = 50_000;
|
|
11
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
12
|
+
const TITLE_BATCH_IDS = 64;
|
|
13
|
+
const identity = service => service?.[symbols.original] ?? service;
|
|
14
|
+
const ordinary = ({ header }) => (header.delegationDepth ?? 0) <= 0 && header.origin !== "subagent";
|
|
15
|
+
const normalizeTitle = value => value.normalize("NFC").trim().replace(/\s+/gu, " ").toLowerCase();
|
|
16
|
+
const fail = message => new Error(`list_sessions: ${message}`);
|
|
17
|
+
|
|
18
|
+
function optionalText(value, name, bytes) {
|
|
19
|
+
if (value === undefined) return undefined;
|
|
20
|
+
if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > bytes) {
|
|
21
|
+
throw fail(`${name} must be a nonempty string of at most ${bytes} UTF-8 bytes`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function filters(args) {
|
|
26
|
+
const title = optionalText(args.titleQuery, "titleQuery", 1024);
|
|
27
|
+
const workspaceId = optionalText(args.workspaceId, "workspaceId", 256);
|
|
28
|
+
const workspacePath = optionalText(args.workspacePath, "workspacePath", 4096);
|
|
29
|
+
if (workspaceId !== undefined && workspacePath !== undefined) throw fail("workspaceId and workspacePath are mutually exclusive");
|
|
30
|
+
if (workspacePath !== undefined && !isAbsolute(workspacePath)) throw fail("workspacePath must be absolute");
|
|
31
|
+
return { titleQuery: title === undefined ? undefined : normalizeTitle(title), workspaceId, workspacePath };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** One plugin instance owns these short-lived result sets. Tokens never authorize a read. */
|
|
35
|
+
export function createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState) {
|
|
36
|
+
const sets = new Map();
|
|
37
|
+
const key = randomBytes(32);
|
|
38
|
+
let sources;
|
|
39
|
+
let disposed = false;
|
|
40
|
+
let count = 0, bytes = 0, expiryTimer;
|
|
41
|
+
const remove = id => {
|
|
42
|
+
const set = sets.get(id);
|
|
43
|
+
if (!set) return;
|
|
44
|
+
count -= set.rows.length; bytes -= set.bytes; sets.delete(id);
|
|
45
|
+
};
|
|
46
|
+
const clear = () => { clearTimeout(expiryTimer); expiryTimer = undefined; sets.clear(); count = 0; bytes = 0; };
|
|
47
|
+
ctx.on?.("dispose", () => { disposed = true; clear(); });
|
|
48
|
+
const services = () => ["sessionQuery", "sessionPersistence", "workspaceRegistry", "sessions"].map(name => identity(ctx.get(name))).concat(identity(ctx.agents));
|
|
49
|
+
const equalSources = (a, b) => a.length === b.length && a.every((value, i) => value === b[i]);
|
|
50
|
+
const sweep = () => { for (const [id, set] of sets) if (Date.now() >= set.expiresAt) remove(id); };
|
|
51
|
+
const scheduleExpiry = () => {
|
|
52
|
+
clearTimeout(expiryTimer);
|
|
53
|
+
expiryTimer = undefined;
|
|
54
|
+
if (!sets.size) return;
|
|
55
|
+
const expiresAt = Math.min(...Array.from(sets.values(), set => set.expiresAt));
|
|
56
|
+
expiryTimer = setTimeout(() => { sweep(); scheduleExpiry(); }, Math.max(1, expiresAt - Date.now()));
|
|
57
|
+
expiryTimer.unref();
|
|
58
|
+
};
|
|
59
|
+
function token(id, offset) {
|
|
60
|
+
const body = Buffer.from(JSON.stringify([id, offset])).toString("base64url");
|
|
61
|
+
return `${body}.${createHmac("sha256", key).update(body).digest("base64url")}`;
|
|
62
|
+
}
|
|
63
|
+
function decode(value) {
|
|
64
|
+
optionalText(value, "cursor", 512);
|
|
65
|
+
try {
|
|
66
|
+
const [body, signature, extra] = value.split(".");
|
|
67
|
+
if (extra !== undefined) throw Error();
|
|
68
|
+
const expected = createHmac("sha256", key).update(body).digest();
|
|
69
|
+
const actual = Buffer.from(signature, "base64url");
|
|
70
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw Error();
|
|
71
|
+
const [id, offset] = JSON.parse(Buffer.from(body, "base64url").toString());
|
|
72
|
+
if (typeof id !== "string" || !Number.isSafeInteger(offset) || offset < 1) throw Error();
|
|
73
|
+
return { id, offset };
|
|
74
|
+
} catch { throw fail("invalid cursor; start a new query without cursor"); }
|
|
75
|
+
}
|
|
76
|
+
async function workspace(filter, signal) {
|
|
77
|
+
if (filter.workspaceId === undefined && filter.workspacePath === undefined) return undefined;
|
|
78
|
+
const registry = ctx.get("workspaceRegistry");
|
|
79
|
+
let result;
|
|
80
|
+
if (filter.workspaceId !== undefined) {
|
|
81
|
+
if (typeof registry?.get !== "function") throw fail("this host cannot look up workspace IDs");
|
|
82
|
+
result = registry.get(filter.workspaceId);
|
|
83
|
+
} else {
|
|
84
|
+
if (typeof registry?.resolveByPath !== "function") throw fail("this host cannot resolve workspace paths");
|
|
85
|
+
try { result = await registry.resolveByPath(filter.workspacePath); }
|
|
86
|
+
catch (cause) { throw fail(`workspacePath could not be resolved (${cause.message}); use an existing registered workspace`); }
|
|
87
|
+
}
|
|
88
|
+
signal?.throwIfAborted();
|
|
89
|
+
if (!result) throw fail("workspace is not registered; use an existing workspace ID or path");
|
|
90
|
+
return { id: String(result.id), path: String(result.path), ids: new Set(result.sessionIds.map(String)) };
|
|
91
|
+
}
|
|
92
|
+
async function matchingTitles(query, records, text, signal) {
|
|
93
|
+
if (typeof query.readTitleSnapshots !== "function") throw fail("titleQuery needs the host's readTitleSnapshots API");
|
|
94
|
+
const titles = new Map();
|
|
95
|
+
for (let start = 0; start < records.length; start += TITLE_BATCH_IDS) {
|
|
96
|
+
const ids = records.slice(start, start + TITLE_BATCH_IDS).map(record => String(record.header.id));
|
|
97
|
+
// One corpus listing per batch. Reserve all permits atomically so no other
|
|
98
|
+
// plugin activity/title read overlaps this batch. The provider owns its
|
|
99
|
+
// internal concurrency (default 4); at most 64 requested IDs can be active.
|
|
100
|
+
const result = await inSlot(() => query.readTitleSnapshots(ids, signal), signal, 4);
|
|
101
|
+
signal?.throwIfAborted();
|
|
102
|
+
if (!Array.isArray(result) || result.length !== ids.length) throw fail("incomplete title batch; no complete matching result is available");
|
|
103
|
+
for (let index = 0; index < ids.length; index++) {
|
|
104
|
+
const id = ids[index], observation = result[index];
|
|
105
|
+
if (observation?.sessionId !== id || observation.status !== "fulfilled" || String(observation.value?.session?.id) !== id) {
|
|
106
|
+
throw fail(`could not read the title of ${id}; no complete matching result is available`);
|
|
107
|
+
}
|
|
108
|
+
// The same read may observe a newer header than the directory scan.
|
|
109
|
+
if (!ordinary({ header: observation.value.session })) throw fail("session visibility changed during title scan; start a new query");
|
|
110
|
+
const title = observation.value.title?.title;
|
|
111
|
+
if (title !== undefined && typeof title !== "string") throw fail(`invalid title snapshot for ${id}`);
|
|
112
|
+
if (title !== undefined && normalizeTitle(title).includes(text)) titles.set(id, title);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return titles;
|
|
116
|
+
}
|
|
117
|
+
return async (args, exec) => {
|
|
118
|
+
exec.signal?.throwIfAborted();
|
|
119
|
+
if (disposed) throw fail("plugin was unloaded; start a new query");
|
|
120
|
+
const currentSources = services();
|
|
121
|
+
if (sources && !equalSources(sources, currentSources)) clear();
|
|
122
|
+
sources = currentSources;
|
|
123
|
+
sweep();
|
|
124
|
+
const query = ctx.get("sessionQuery");
|
|
125
|
+
if (query === undefined) throw fail("needs session lookup, which this DSH does not offer");
|
|
126
|
+
if (args.limit !== undefined && (typeof args.limit !== "number" || !Number.isFinite(args.limit))) throw fail("limit must be a finite number");
|
|
127
|
+
const limit = Math.max(1, Math.min(100, Math.trunc(args.limit ?? 20)));
|
|
128
|
+
// Agent.id is the existing public tool-execution identity; arguments cannot supply it.
|
|
129
|
+
const owner = typeof exec.agent?.id === "string" && exec.agent.id ? exec.agent.id : undefined;
|
|
130
|
+
let filter = filters(args), set, offset = 0, setId;
|
|
131
|
+
if (args.cursor !== undefined) {
|
|
132
|
+
({ id: setId, offset } = decode(args.cursor));
|
|
133
|
+
set = sets.get(setId);
|
|
134
|
+
if (!set) throw fail("cursor expired, was evicted, or belongs to another plugin/host; start a new query without cursor");
|
|
135
|
+
if (!owner || owner !== set.owner) throw fail("cursor belongs to a different calling session");
|
|
136
|
+
if (offset >= set.rows.length) throw fail("invalid cursor offset");
|
|
137
|
+
if (filter.titleQuery !== undefined && filter.titleQuery !== set.filter.titleQuery) throw fail("cursor titleQuery does not match its original query");
|
|
138
|
+
filter = { ...set.filter, ...(filter.workspaceId !== undefined || filter.workspacePath !== undefined ? { workspaceId: filter.workspaceId, workspacePath: filter.workspacePath } : {}) };
|
|
139
|
+
}
|
|
140
|
+
const selected = await workspace(filter, exec.signal);
|
|
141
|
+
if (set && (selected?.id !== set.workspaceId || selected?.path !== set.workspacePath)) throw fail("cursor workspace does not match its original query");
|
|
142
|
+
const records = await query.listSessions(exec.signal);
|
|
143
|
+
exec.signal?.throwIfAborted();
|
|
144
|
+
sortByActivity.prune(records);
|
|
145
|
+
let candidates = records.filter(record => ordinary(record) && (!selected || selected.ids.has(String(record.header.id))));
|
|
146
|
+
const byId = new Map(candidates.map(record => [String(record.header.id), record]));
|
|
147
|
+
if (set) {
|
|
148
|
+
// Recheck the entire frozen range, not just the requested slice. Never silently skip.
|
|
149
|
+
if (set.rows.some(row => !byId.has(row.id))) {
|
|
150
|
+
remove(setId);
|
|
151
|
+
throw fail("result set contains a session no longer visible or in this workspace; start a new query");
|
|
152
|
+
}
|
|
153
|
+
} else {
|
|
154
|
+
if ((owner || filter.titleQuery !== undefined) && candidates.length > MAX_SET_IDS) throw fail(`candidate set exceeds ${MAX_SET_IDS} sessions; narrow the workspace filter`);
|
|
155
|
+
const titles = filter.titleQuery === undefined ? undefined : await matchingTitles(query, candidates, filter.titleQuery, exec.signal);
|
|
156
|
+
if (titles) candidates = candidates.filter(record => titles.has(String(record.header.id)));
|
|
157
|
+
const ordered = await sortByActivity(candidates, exec.signal, records);
|
|
158
|
+
const rows = ordered.map(record => ({ id: String(record.header.id), ...(titles ? { title: titles.get(String(record.header.id)) } : {}) }));
|
|
159
|
+
set = { owner, filter: { titleQuery: filter.titleQuery, workspaceId: selected?.id }, rows, workspaceId: selected?.id, workspacePath: selected?.path, createdAt: Date.now() };
|
|
160
|
+
set.expiresAt = set.createdAt + TTL;
|
|
161
|
+
set.bytes = Buffer.byteLength(JSON.stringify(set));
|
|
162
|
+
if (owner && rows.length > limit && set.bytes > MAX_BYTES) throw fail("result set exceeds the 8 MiB metadata budget; narrow the query");
|
|
163
|
+
}
|
|
164
|
+
const page = set.rows.slice(offset, offset + limit);
|
|
165
|
+
let communication;
|
|
166
|
+
try {
|
|
167
|
+
communication = await communicationPermissions(ctx).statuses(trustedSource(exec), page.map(row => row.id));
|
|
168
|
+
} catch {
|
|
169
|
+
communication = page.map(() => unknownCommunication());
|
|
170
|
+
}
|
|
171
|
+
exec.signal?.throwIfAborted();
|
|
172
|
+
const listed = [];
|
|
173
|
+
for (const [pageIndex, row] of page.entries()) {
|
|
174
|
+
exec.signal?.throwIfAborted();
|
|
175
|
+
const header = byId.get(row.id).header;
|
|
176
|
+
let title = row.title;
|
|
177
|
+
if (set.filter.titleQuery === undefined) try {
|
|
178
|
+
// Legacy no-query listing keeps best-effort titles and reads only this page.
|
|
179
|
+
title = (await inSlot(() => query.readTitle(row.id, exec.signal), exec.signal))?.title;
|
|
180
|
+
} catch {}
|
|
181
|
+
exec.signal?.throwIfAborted();
|
|
182
|
+
listed.push({ sessionId: row.id, communication: communication[pageIndex],
|
|
183
|
+
...title === undefined || title === "" ? {} : { title: String(title) },
|
|
184
|
+
...header.cwd === undefined ? {} : { cwd: String(header.cwd) },
|
|
185
|
+
state: sessionState(ctx, row.id), ...row.id === owner ? { current: true } : {},
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
exec.signal?.throwIfAborted();
|
|
189
|
+
if (disposed) throw fail("plugin was unloaded; start a new query");
|
|
190
|
+
const hasMore = offset + listed.length < set.rows.length;
|
|
191
|
+
if (setId || (hasMore && owner)) {
|
|
192
|
+
if (!equalSources(currentSources, services())) { clear(); throw fail("host services changed; start a new query"); }
|
|
193
|
+
if (Date.now() >= set.expiresAt) { if (setId) remove(setId); throw fail("cursor expired while reading; start a new query"); }
|
|
194
|
+
if (!setId) {
|
|
195
|
+
sweep();
|
|
196
|
+
while (sets.size >= MAX_SETS || count + set.rows.length > MAX_IDS || bytes + set.bytes > MAX_BYTES) remove(sets.keys().next().value);
|
|
197
|
+
setId = randomUUID(); count += set.rows.length; bytes += set.bytes;
|
|
198
|
+
} else {
|
|
199
|
+
// An overlapping call may have evicted this set while this page was read.
|
|
200
|
+
if (sets.get(setId) !== set) throw fail("cursor was evicted while reading; start a new query");
|
|
201
|
+
sets.delete(setId);
|
|
202
|
+
}
|
|
203
|
+
sets.set(setId, set);
|
|
204
|
+
scheduleExpiry();
|
|
205
|
+
}
|
|
206
|
+
return { sessions: listed, total: records.length, matchedTotal: set.rows.length,
|
|
207
|
+
...(setId ? { resultSetCreatedAt: set.createdAt, resultSetExpiresAt: set.expiresAt,
|
|
208
|
+
...(hasMore ? { nextCursor: token(setId, offset + listed.length) } : {}) } : {}),
|
|
209
|
+
...(hasMore && !owner ? { paginationUnavailable: "A calling Agent identity is required to continue; run list_sessions through the host tool runtime." } : {}),
|
|
210
|
+
...(selected ? { workspaceId: selected.id, workspacePath: selected.path } : {}),
|
|
211
|
+
};
|
|
212
|
+
};
|
|
213
|
+
}
|