@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
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { expandAssistantStream, joinAssistantStreamText } from '@deepseek-ai/dsh-llm';
|
|
3
|
+
|
|
4
|
+
// These are a plugin-owned fold/cache of public rc.2 events, not a host
|
|
5
|
+
// message-result API. Checkpoints are disposable; the event log is authoritative.
|
|
6
|
+
export const receiptProjectionKey = 'sessionToolsReceipts';
|
|
7
|
+
const receiptSchema = z.object({
|
|
8
|
+
state: z.enum(['queued', 'delivered', 'discarded']),
|
|
9
|
+
turn: z.number().nullable(), admitted: z.boolean(), ambiguous: z.boolean(), inherited: z.boolean(),
|
|
10
|
+
});
|
|
11
|
+
export const receiptProjection = {
|
|
12
|
+
key: receiptProjectionKey,
|
|
13
|
+
stateVersion: 1,
|
|
14
|
+
stateSchema: z.object({
|
|
15
|
+
seq: z.number(), inheritedEventCount: z.number(), valid: z.boolean(),
|
|
16
|
+
openTurn: z.number().nullable(),
|
|
17
|
+
nextTurn: z.array(z.string()), nextStep: z.array(z.string()),
|
|
18
|
+
messages: z.record(z.string(), receiptSchema),
|
|
19
|
+
turns: z.record(z.string(), z.string()),
|
|
20
|
+
}),
|
|
21
|
+
init: (_header, inheritedEventCount = 0) => ({
|
|
22
|
+
seq: -1, inheritedEventCount, valid: true, openTurn: null,
|
|
23
|
+
nextTurn: [], nextStep: [], messages: {}, turns: {},
|
|
24
|
+
}),
|
|
25
|
+
apply: foldReceiptEvent,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** Pure, JSON-only projection. Invalid/incomplete logs fail attribution closed. */
|
|
29
|
+
function foldReceiptEvent(previous, event) {
|
|
30
|
+
if (!previous.valid) return previous;
|
|
31
|
+
const state = { ...previous, seq: event.seq };
|
|
32
|
+
const invalid = () => ({ ...state, valid: false });
|
|
33
|
+
if (!Number.isSafeInteger(event.seq) || event.seq !== previous.seq + 1) return invalid();
|
|
34
|
+
const data = event.data ?? {};
|
|
35
|
+
if (event.type === 'turn/start') {
|
|
36
|
+
if (state.openTurn !== null || !Number.isSafeInteger(data.turn) || data.turn <= 0 || Object.hasOwn(state.turns, data.turn)) return invalid();
|
|
37
|
+
return { ...state, openTurn: data.turn };
|
|
38
|
+
}
|
|
39
|
+
if (event.type === 'turn/end') {
|
|
40
|
+
if (state.openTurn !== data.turn || typeof data.reason?.kind !== 'string') return invalid();
|
|
41
|
+
return { ...state, openTurn: null, turns: { ...state.turns, [data.turn]: data.reason.kind } };
|
|
42
|
+
}
|
|
43
|
+
if (event.type === 'agent/inbox/spliced') {
|
|
44
|
+
const key = data.target === 'next-turn' ? 'nextTurn' : data.target === 'next-step' ? 'nextStep' : undefined;
|
|
45
|
+
if (!key) return invalid();
|
|
46
|
+
const list = state[key], count = data.removedCount ?? 0;
|
|
47
|
+
if (!Number.isSafeInteger(data.start) || data.start < 0 || data.start > list.length || !Number.isSafeInteger(count) || count < 0 || data.start + count > list.length || !Array.isArray(data.inserted)) return invalid();
|
|
48
|
+
if (data.outcome !== undefined && data.outcome !== 'canceled') return invalid();
|
|
49
|
+
const inserted = data.inserted.map(message => message?.id);
|
|
50
|
+
if (inserted.some(id => typeof id !== 'string' || id === '')) return invalid();
|
|
51
|
+
const removed = list.slice(data.start, data.start + count);
|
|
52
|
+
const next = list.toSpliced(data.start, count, ...inserted);
|
|
53
|
+
const pending = [...next, ...state[key === 'nextTurn' ? 'nextStep' : 'nextTurn']];
|
|
54
|
+
if (new Set(pending).size !== pending.length) return invalid();
|
|
55
|
+
const messages = { ...state.messages };
|
|
56
|
+
for (const id of removed) {
|
|
57
|
+
// Public claim() uses a pure deletion inside the already-open turn;
|
|
58
|
+
// ordinary remove/replace/clear logs outcome:canceled (discarded).
|
|
59
|
+
if (data.outcome === undefined && (state.openTurn === null || inserted.length !== 0)) return invalid();
|
|
60
|
+
messages[id] = { ...messages[id], state: data.outcome === 'canceled' ? 'discarded' : 'delivered', turn: data.outcome === 'canceled' ? null : state.openTurn };
|
|
61
|
+
}
|
|
62
|
+
for (const id of inserted) {
|
|
63
|
+
messages[id] = { state: 'queued', turn: null, admitted: false, ambiguous: Object.hasOwn(messages, id), inherited: event.seq < state.inheritedEventCount };
|
|
64
|
+
}
|
|
65
|
+
return { ...state, [key]: next, messages };
|
|
66
|
+
}
|
|
67
|
+
if (event.type === 'user/message') {
|
|
68
|
+
const message = state.messages[data.id];
|
|
69
|
+
if (!Object.hasOwn(state.messages, data.id)) return state;
|
|
70
|
+
if (message.state !== 'delivered' || message.turn !== state.openTurn || message.admitted) {
|
|
71
|
+
return { ...state, messages: { ...state.messages, [data.id]: { ...message, ambiguous: true } } };
|
|
72
|
+
}
|
|
73
|
+
return { ...state, messages: { ...state.messages, [data.id]: { ...message, admitted: true } } };
|
|
74
|
+
}
|
|
75
|
+
return state;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function foldReceipts(events, inheritedEventCount = 0) {
|
|
79
|
+
return events.reduce(foldReceiptEvent, receiptProjection.init(undefined, inheritedEventCount));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Same output selection as rc.2 AssistantOutputFold, restricted to one turn. */
|
|
83
|
+
export function turnOutput(events, turn) {
|
|
84
|
+
let message;
|
|
85
|
+
const partial = [];
|
|
86
|
+
let inside = false;
|
|
87
|
+
for (const event of events) {
|
|
88
|
+
if (event.type === 'turn/start' && event.data.turn === turn) inside = true;
|
|
89
|
+
if (event.type === 'turn/end' && event.data.turn === turn) break;
|
|
90
|
+
if (!inside || event.data?.turn !== turn || !['assistant/message', 'assistant/attempt'].includes(event.type)) continue;
|
|
91
|
+
if (event.type === 'assistant/message' && event.data.message?.content?.length > 0) message = event.data.message.content;
|
|
92
|
+
const stream = event.data.stream ?? [];
|
|
93
|
+
// Public stream readers trust types; validate persisted records first.
|
|
94
|
+
expandAssistantStream(stream);
|
|
95
|
+
partial.push(joinAssistantStreamText(stream));
|
|
96
|
+
}
|
|
97
|
+
const text = message === undefined ? partial.join('') : message.filter(block => block.type === 'text').map(block => block.text).join('');
|
|
98
|
+
return text.trim() === '' ? undefined : text;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function messageReceipt(state, messageId, events) {
|
|
102
|
+
const unknown = note => ({ messageStatus: 'unknown', completed: false, attributionNote: note });
|
|
103
|
+
if (!state.valid) return unknown('The event log is incomplete or cannot reliably identify this message.');
|
|
104
|
+
if (!Object.hasOwn(state.messages, messageId)) return unknown('No durable receipt for this message was found.');
|
|
105
|
+
const message = state.messages[messageId];
|
|
106
|
+
if (message.ambiguous || message.inherited) return unknown('This identity is reused or belongs to inherited history; its result cannot be attributed.');
|
|
107
|
+
const base = { messageStatus: message.state, completed: false, ...(message.turn === null ? {} : { turn: message.turn }) };
|
|
108
|
+
if (message.turn === null) return base;
|
|
109
|
+
const kind = state.turns[message.turn];
|
|
110
|
+
if (kind === undefined) return base;
|
|
111
|
+
const ended = { ...base, turnEndKind: kind };
|
|
112
|
+
if (kind === 'completed' && !message.admitted) return { ...ended, ...unknown('The turn ended without admitting this message to the model.') };
|
|
113
|
+
const messageStatus = { completed: 'turnCompleted', aborted: 'cancelled', blocked: 'blocked', error: 'failed', interrupted: 'interrupted', 'max-tokens': 'incomplete' }[kind] ?? 'unknown';
|
|
114
|
+
if (messageStatus !== 'turnCompleted') return { ...ended, messageStatus };
|
|
115
|
+
try {
|
|
116
|
+
const output = turnOutput(events, message.turn);
|
|
117
|
+
return { ...ended, messageStatus, completed: true, ...(output === undefined ? {} : { output }) };
|
|
118
|
+
} catch {
|
|
119
|
+
return { ...ended, ...unknown('The recorded output could not be decoded reliably.') };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { symbols } from "@deepseek-ai/cordis";
|
|
2
|
+
|
|
3
|
+
// Use events whose rc.2 meaning is independent of crash-recovery repair.
|
|
4
|
+
// Bare step/tool completion records do not independently advance activity.
|
|
5
|
+
const activityEvents = new Set([
|
|
6
|
+
"user/message", "assistant/message", "assistant/attempt",
|
|
7
|
+
"turn/start", "step/start", "tool/call"
|
|
8
|
+
]);
|
|
9
|
+
const executedTurnEnds = new Set(["completed", "aborted", "blocked", "error", "max-tokens"]);
|
|
10
|
+
|
|
11
|
+
export function conversationActivity(events, createdAt, inheritedEventCount = 0) {
|
|
12
|
+
let latest;
|
|
13
|
+
for (let index = inheritedEventCount; index < events.length; index++) {
|
|
14
|
+
const event = events[index];
|
|
15
|
+
const newInput = event.type === "agent/inbox/spliced" && event.data.inserted?.length > 0;
|
|
16
|
+
const executionEnded = event.type === "turn/end" && executedTurnEnds.has(event.data.reason?.kind);
|
|
17
|
+
if ((activityEvents.has(event.type) || newInput || executionEnded) && Number.isFinite(event.time)) {
|
|
18
|
+
latest = latest === undefined ? event.time : Math.max(latest, event.time);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return latest ?? (Number.isFinite(createdAt) ? createdAt : 0);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Four shared permits. A title batch takes all four atomically, never partial permits. */
|
|
25
|
+
export function readSlots() {
|
|
26
|
+
let active = 0;
|
|
27
|
+
const waiting = [];
|
|
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");
|
|
37
|
+
signal?.throwIfAborted();
|
|
38
|
+
await new Promise((resolve, reject) => {
|
|
39
|
+
const entry = { weight, start: () => { signal?.removeEventListener("abort", abort); resolve(); } };
|
|
40
|
+
const abort = () => {
|
|
41
|
+
const index = waiting.indexOf(entry);
|
|
42
|
+
if (index >= 0) waiting.splice(index, 1);
|
|
43
|
+
reject(signal.reason);
|
|
44
|
+
pump();
|
|
45
|
+
};
|
|
46
|
+
waiting.push(entry);
|
|
47
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
48
|
+
pump();
|
|
49
|
+
});
|
|
50
|
+
try {
|
|
51
|
+
signal?.throwIfAborted();
|
|
52
|
+
return await read();
|
|
53
|
+
} finally {
|
|
54
|
+
active -= weight;
|
|
55
|
+
pump();
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const identity = service => service?.[symbols.original] ?? service;
|
|
61
|
+
|
|
62
|
+
/** Cache only the derived number, never a log, a read handle, or an Agent. */
|
|
63
|
+
export function createActivitySorter(ctx, inSlot = readSlots()) {
|
|
64
|
+
const cache = new Map();
|
|
65
|
+
const liveCache = new WeakMap();
|
|
66
|
+
async function activity(record, signal) {
|
|
67
|
+
const id = String(record.header.id);
|
|
68
|
+
const live = ctx.get("sessions")?.get(id) ?? ctx.agents.get(id)?.session;
|
|
69
|
+
if (typeof live?.snapshotEvents === "function") {
|
|
70
|
+
const events = live.snapshotEvents();
|
|
71
|
+
const source = identity(live);
|
|
72
|
+
const previous = liveCache.get(source);
|
|
73
|
+
if (previous?.version === events.length) return previous.time;
|
|
74
|
+
const time = conversationActivity(events, live.header.createdAt, live.inheritedEventCount);
|
|
75
|
+
liveCache.set(source, { version: events.length, time });
|
|
76
|
+
return time;
|
|
77
|
+
}
|
|
78
|
+
const persistence = ctx.get("sessionPersistence");
|
|
79
|
+
if (persistence !== undefined) {
|
|
80
|
+
const source = identity(persistence);
|
|
81
|
+
// Revisions are comparable only for the same service instance and id.
|
|
82
|
+
const version = (await persistence.stat?.(id, { signal }))?.revision;
|
|
83
|
+
signal?.throwIfAborted();
|
|
84
|
+
const previous = cache.get(id);
|
|
85
|
+
if (version !== undefined && previous?.source === source && previous.version === version) return previous.time;
|
|
86
|
+
const reader = await persistence.open(id, "read", { signal });
|
|
87
|
+
let time;
|
|
88
|
+
try {
|
|
89
|
+
signal?.throwIfAborted();
|
|
90
|
+
const { events } = await reader.read(0, undefined, { signal });
|
|
91
|
+
signal?.throwIfAborted();
|
|
92
|
+
time = conversationActivity(events, reader.header.createdAt, reader.inheritedEventCount);
|
|
93
|
+
} finally {
|
|
94
|
+
await reader.close();
|
|
95
|
+
}
|
|
96
|
+
if (version !== undefined) cache.set(id, { source, version, time });
|
|
97
|
+
return time;
|
|
98
|
+
}
|
|
99
|
+
// Query-only hosts have no revision token, so never reuse a cold result.
|
|
100
|
+
const log = await ctx.get("sessionQuery").readSession(id);
|
|
101
|
+
signal?.throwIfAborted();
|
|
102
|
+
return conversationActivity(log.events, record.header.createdAt, log.inheritedEventCount);
|
|
103
|
+
}
|
|
104
|
+
const sort = async (records, signal, directory = records) => {
|
|
105
|
+
signal?.throwIfAborted();
|
|
106
|
+
sort.prune(directory);
|
|
107
|
+
// Wait for every observation to close, including after an error/abort.
|
|
108
|
+
const ordered = [];
|
|
109
|
+
let next = 0;
|
|
110
|
+
let failed = false;
|
|
111
|
+
const worker = async () => {
|
|
112
|
+
try {
|
|
113
|
+
while (!failed && next < records.length) {
|
|
114
|
+
const index = next++;
|
|
115
|
+
const record = records[index];
|
|
116
|
+
const time = await inSlot(() => activity(record, signal), signal);
|
|
117
|
+
ordered.push({ record, index, time });
|
|
118
|
+
}
|
|
119
|
+
} catch (error) { failed = true; throw error; }
|
|
120
|
+
};
|
|
121
|
+
const results = await Promise.allSettled(Array.from({ length: Math.min(4, records.length) }, worker));
|
|
122
|
+
const failure = results.find(result => result.status === "rejected");
|
|
123
|
+
if (failure) throw failure.reason;
|
|
124
|
+
signal?.throwIfAborted();
|
|
125
|
+
return ordered
|
|
126
|
+
.sort((a, b) => b.time - a.time || a.index - b.index)
|
|
127
|
+
.map(({ record }) => record);
|
|
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;
|
|
135
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
3
|
+
import { symbols } from "@deepseek-ai/cordis";
|
|
4
|
+
|
|
5
|
+
// Resource guards, not measured throughput promises. No event/log/Agent is retained.
|
|
6
|
+
const TTL = 5 * 60_000;
|
|
7
|
+
const MAX_SETS = 16;
|
|
8
|
+
const MAX_SET_IDS = 10_000;
|
|
9
|
+
const MAX_IDS = 50_000;
|
|
10
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
const TITLE_BATCH_IDS = 64;
|
|
12
|
+
const identity = service => service?.[symbols.original] ?? service;
|
|
13
|
+
const ordinary = ({ header }) => (header.delegationDepth ?? 0) <= 0 && header.origin !== "subagent";
|
|
14
|
+
const normalizeTitle = value => value.normalize("NFC").trim().replace(/\s+/gu, " ").toLowerCase();
|
|
15
|
+
const fail = message => new Error(`list_sessions: ${message}`);
|
|
16
|
+
|
|
17
|
+
function optionalText(value, name, bytes) {
|
|
18
|
+
if (value === undefined) return undefined;
|
|
19
|
+
if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > bytes) {
|
|
20
|
+
throw fail(`${name} must be a nonempty string of at most ${bytes} UTF-8 bytes`);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function filters(args) {
|
|
25
|
+
const title = optionalText(args.titleQuery, "titleQuery", 1024);
|
|
26
|
+
const workspaceId = optionalText(args.workspaceId, "workspaceId", 256);
|
|
27
|
+
const workspacePath = optionalText(args.workspacePath, "workspacePath", 4096);
|
|
28
|
+
if (workspaceId !== undefined && workspacePath !== undefined) throw fail("workspaceId and workspacePath are mutually exclusive");
|
|
29
|
+
if (workspacePath !== undefined && !isAbsolute(workspacePath)) throw fail("workspacePath must be absolute");
|
|
30
|
+
return { titleQuery: title === undefined ? undefined : normalizeTitle(title), workspaceId, workspacePath };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** One plugin instance owns these short-lived result sets. Tokens never authorize a read. */
|
|
34
|
+
export function createSessionDiscovery(ctx, sortByActivity, inSlot, sessionState) {
|
|
35
|
+
const sets = new Map();
|
|
36
|
+
const key = randomBytes(32);
|
|
37
|
+
let sources;
|
|
38
|
+
let disposed = false;
|
|
39
|
+
let count = 0, bytes = 0, expiryTimer;
|
|
40
|
+
const remove = id => {
|
|
41
|
+
const set = sets.get(id);
|
|
42
|
+
if (!set) return;
|
|
43
|
+
count -= set.rows.length; bytes -= set.bytes; sets.delete(id);
|
|
44
|
+
};
|
|
45
|
+
const clear = () => { clearTimeout(expiryTimer); expiryTimer = undefined; sets.clear(); count = 0; bytes = 0; };
|
|
46
|
+
ctx.on?.("dispose", () => { disposed = true; clear(); });
|
|
47
|
+
const services = () => ["sessionQuery", "sessionPersistence", "workspaceRegistry", "sessions"].map(name => identity(ctx.get(name))).concat(identity(ctx.agents));
|
|
48
|
+
const equalSources = (a, b) => a.length === b.length && a.every((value, i) => value === b[i]);
|
|
49
|
+
const sweep = () => { for (const [id, set] of sets) if (Date.now() >= set.expiresAt) remove(id); };
|
|
50
|
+
const scheduleExpiry = () => {
|
|
51
|
+
clearTimeout(expiryTimer);
|
|
52
|
+
expiryTimer = undefined;
|
|
53
|
+
if (!sets.size) return;
|
|
54
|
+
const expiresAt = Math.min(...Array.from(sets.values(), set => set.expiresAt));
|
|
55
|
+
expiryTimer = setTimeout(() => { sweep(); scheduleExpiry(); }, Math.max(1, expiresAt - Date.now()));
|
|
56
|
+
expiryTimer.unref();
|
|
57
|
+
};
|
|
58
|
+
function token(id, offset) {
|
|
59
|
+
const body = Buffer.from(JSON.stringify([id, offset])).toString("base64url");
|
|
60
|
+
return `${body}.${createHmac("sha256", key).update(body).digest("base64url")}`;
|
|
61
|
+
}
|
|
62
|
+
function decode(value) {
|
|
63
|
+
optionalText(value, "cursor", 512);
|
|
64
|
+
try {
|
|
65
|
+
const [body, signature, extra] = value.split(".");
|
|
66
|
+
if (extra !== undefined) throw Error();
|
|
67
|
+
const expected = createHmac("sha256", key).update(body).digest();
|
|
68
|
+
const actual = Buffer.from(signature, "base64url");
|
|
69
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw Error();
|
|
70
|
+
const [id, offset] = JSON.parse(Buffer.from(body, "base64url").toString());
|
|
71
|
+
if (typeof id !== "string" || !Number.isSafeInteger(offset) || offset < 1) throw Error();
|
|
72
|
+
return { id, offset };
|
|
73
|
+
} catch { throw fail("invalid cursor; start a new query without cursor"); }
|
|
74
|
+
}
|
|
75
|
+
async function workspace(filter, signal) {
|
|
76
|
+
if (filter.workspaceId === undefined && filter.workspacePath === undefined) return undefined;
|
|
77
|
+
const registry = ctx.get("workspaceRegistry");
|
|
78
|
+
let result;
|
|
79
|
+
if (filter.workspaceId !== undefined) {
|
|
80
|
+
if (typeof registry?.get !== "function") throw fail("this host cannot look up workspace IDs");
|
|
81
|
+
result = registry.get(filter.workspaceId);
|
|
82
|
+
} else {
|
|
83
|
+
if (typeof registry?.resolveByPath !== "function") throw fail("this host cannot resolve workspace paths");
|
|
84
|
+
try { result = await registry.resolveByPath(filter.workspacePath); }
|
|
85
|
+
catch (cause) { throw fail(`workspacePath could not be resolved (${cause.message}); use an existing registered workspace`); }
|
|
86
|
+
}
|
|
87
|
+
signal?.throwIfAborted();
|
|
88
|
+
if (!result) throw fail("workspace is not registered; use an existing workspace ID or path");
|
|
89
|
+
return { id: String(result.id), path: String(result.path), ids: new Set(result.sessionIds.map(String)) };
|
|
90
|
+
}
|
|
91
|
+
async function matchingTitles(query, records, text, signal) {
|
|
92
|
+
if (typeof query.readTitleSnapshots !== "function") throw fail("titleQuery needs the host's readTitleSnapshots API");
|
|
93
|
+
const titles = new Map();
|
|
94
|
+
for (let start = 0; start < records.length; start += TITLE_BATCH_IDS) {
|
|
95
|
+
const ids = records.slice(start, start + TITLE_BATCH_IDS).map(record => String(record.header.id));
|
|
96
|
+
// One corpus listing per batch. Reserve all permits atomically so no other
|
|
97
|
+
// plugin activity/title read overlaps this batch. The provider owns its
|
|
98
|
+
// internal concurrency (default 4); at most 64 requested IDs can be active.
|
|
99
|
+
const result = await inSlot(() => query.readTitleSnapshots(ids, signal), signal, 4);
|
|
100
|
+
signal?.throwIfAborted();
|
|
101
|
+
if (!Array.isArray(result) || result.length !== ids.length) throw fail("incomplete title batch; no complete matching result is available");
|
|
102
|
+
for (let index = 0; index < ids.length; index++) {
|
|
103
|
+
const id = ids[index], observation = result[index];
|
|
104
|
+
if (observation?.sessionId !== id || observation.status !== "fulfilled" || String(observation.value?.session?.id) !== id) {
|
|
105
|
+
throw fail(`could not read the title of ${id}; no complete matching result is available`);
|
|
106
|
+
}
|
|
107
|
+
// The same read may observe a newer header than the directory scan.
|
|
108
|
+
if (!ordinary({ header: observation.value.session })) throw fail("session visibility changed during title scan; start a new query");
|
|
109
|
+
const title = observation.value.title?.title;
|
|
110
|
+
if (title !== undefined && typeof title !== "string") throw fail(`invalid title snapshot for ${id}`);
|
|
111
|
+
if (title !== undefined && normalizeTitle(title).includes(text)) titles.set(id, title);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return titles;
|
|
115
|
+
}
|
|
116
|
+
return async (args, exec) => {
|
|
117
|
+
exec.signal?.throwIfAborted();
|
|
118
|
+
if (disposed) throw fail("plugin was unloaded; start a new query");
|
|
119
|
+
const currentSources = services();
|
|
120
|
+
if (sources && !equalSources(sources, currentSources)) clear();
|
|
121
|
+
sources = currentSources;
|
|
122
|
+
sweep();
|
|
123
|
+
const query = ctx.get("sessionQuery");
|
|
124
|
+
if (query === undefined) throw fail("needs session lookup, which this DSH does not offer");
|
|
125
|
+
if (args.limit !== undefined && (typeof args.limit !== "number" || !Number.isFinite(args.limit))) throw fail("limit must be a finite number");
|
|
126
|
+
const limit = Math.max(1, Math.min(100, Math.trunc(args.limit ?? 20)));
|
|
127
|
+
// Agent.id is the existing public tool-execution identity; arguments cannot supply it.
|
|
128
|
+
const owner = typeof exec.agent?.id === "string" && exec.agent.id ? exec.agent.id : undefined;
|
|
129
|
+
let filter = filters(args), set, offset = 0, setId;
|
|
130
|
+
if (args.cursor !== undefined) {
|
|
131
|
+
({ id: setId, offset } = decode(args.cursor));
|
|
132
|
+
set = sets.get(setId);
|
|
133
|
+
if (!set) throw fail("cursor expired, was evicted, or belongs to another plugin/host; start a new query without cursor");
|
|
134
|
+
if (!owner || owner !== set.owner) throw fail("cursor belongs to a different calling session");
|
|
135
|
+
if (offset >= set.rows.length) throw fail("invalid cursor offset");
|
|
136
|
+
if (filter.titleQuery !== undefined && filter.titleQuery !== set.filter.titleQuery) throw fail("cursor titleQuery does not match its original query");
|
|
137
|
+
filter = { ...set.filter, ...(filter.workspaceId !== undefined || filter.workspacePath !== undefined ? { workspaceId: filter.workspaceId, workspacePath: filter.workspacePath } : {}) };
|
|
138
|
+
}
|
|
139
|
+
const selected = await workspace(filter, exec.signal);
|
|
140
|
+
if (set && (selected?.id !== set.workspaceId || selected?.path !== set.workspacePath)) throw fail("cursor workspace does not match its original query");
|
|
141
|
+
const records = await query.listSessions(exec.signal);
|
|
142
|
+
exec.signal?.throwIfAborted();
|
|
143
|
+
sortByActivity.prune(records);
|
|
144
|
+
let candidates = records.filter(record => ordinary(record) && (!selected || selected.ids.has(String(record.header.id))));
|
|
145
|
+
const byId = new Map(candidates.map(record => [String(record.header.id), record]));
|
|
146
|
+
if (set) {
|
|
147
|
+
// Recheck the entire frozen range, not just the requested slice. Never silently skip.
|
|
148
|
+
if (set.rows.some(row => !byId.has(row.id))) {
|
|
149
|
+
remove(setId);
|
|
150
|
+
throw fail("result set contains a session no longer visible or in this workspace; start a new query");
|
|
151
|
+
}
|
|
152
|
+
} else {
|
|
153
|
+
if ((owner || filter.titleQuery !== undefined) && candidates.length > MAX_SET_IDS) throw fail(`candidate set exceeds ${MAX_SET_IDS} sessions; narrow the workspace filter`);
|
|
154
|
+
const titles = filter.titleQuery === undefined ? undefined : await matchingTitles(query, candidates, filter.titleQuery, exec.signal);
|
|
155
|
+
if (titles) candidates = candidates.filter(record => titles.has(String(record.header.id)));
|
|
156
|
+
const ordered = await sortByActivity(candidates, exec.signal, records);
|
|
157
|
+
const rows = ordered.map(record => ({ id: String(record.header.id), ...(titles ? { title: titles.get(String(record.header.id)) } : {}) }));
|
|
158
|
+
set = { owner, filter: { titleQuery: filter.titleQuery, workspaceId: selected?.id }, rows, workspaceId: selected?.id, workspacePath: selected?.path, createdAt: Date.now() };
|
|
159
|
+
set.expiresAt = set.createdAt + TTL;
|
|
160
|
+
set.bytes = Buffer.byteLength(JSON.stringify(set));
|
|
161
|
+
if (owner && rows.length > limit && set.bytes > MAX_BYTES) throw fail("result set exceeds the 8 MiB metadata budget; narrow the query");
|
|
162
|
+
}
|
|
163
|
+
const listed = [];
|
|
164
|
+
for (const row of set.rows.slice(offset, offset + limit)) {
|
|
165
|
+
exec.signal?.throwIfAborted();
|
|
166
|
+
const header = byId.get(row.id).header;
|
|
167
|
+
let title = row.title;
|
|
168
|
+
if (set.filter.titleQuery === undefined) try {
|
|
169
|
+
// Legacy no-query listing keeps best-effort titles and reads only this page.
|
|
170
|
+
title = (await inSlot(() => query.readTitle(row.id, exec.signal), exec.signal))?.title;
|
|
171
|
+
} catch {}
|
|
172
|
+
exec.signal?.throwIfAborted();
|
|
173
|
+
listed.push({ sessionId: row.id,
|
|
174
|
+
...title === undefined || title === "" ? {} : { title: String(title) },
|
|
175
|
+
...header.cwd === undefined ? {} : { cwd: String(header.cwd) },
|
|
176
|
+
state: sessionState(ctx, row.id), ...row.id === owner ? { current: true } : {},
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
exec.signal?.throwIfAborted();
|
|
180
|
+
if (disposed) throw fail("plugin was unloaded; start a new query");
|
|
181
|
+
const hasMore = offset + listed.length < set.rows.length;
|
|
182
|
+
if (setId || (hasMore && owner)) {
|
|
183
|
+
if (!equalSources(currentSources, services())) { clear(); throw fail("host services changed; start a new query"); }
|
|
184
|
+
if (Date.now() >= set.expiresAt) { if (setId) remove(setId); throw fail("cursor expired while reading; start a new query"); }
|
|
185
|
+
if (!setId) {
|
|
186
|
+
sweep();
|
|
187
|
+
while (sets.size >= MAX_SETS || count + set.rows.length > MAX_IDS || bytes + set.bytes > MAX_BYTES) remove(sets.keys().next().value);
|
|
188
|
+
setId = randomUUID(); count += set.rows.length; bytes += set.bytes;
|
|
189
|
+
} else {
|
|
190
|
+
// An overlapping call may have evicted this set while this page was read.
|
|
191
|
+
if (sets.get(setId) !== set) throw fail("cursor was evicted while reading; start a new query");
|
|
192
|
+
sets.delete(setId);
|
|
193
|
+
}
|
|
194
|
+
sets.set(setId, set);
|
|
195
|
+
scheduleExpiry();
|
|
196
|
+
}
|
|
197
|
+
return { sessions: listed, total: records.length, matchedTotal: set.rows.length,
|
|
198
|
+
...(setId ? { resultSetCreatedAt: set.createdAt, resultSetExpiresAt: set.expiresAt,
|
|
199
|
+
...(hasMore ? { nextCursor: token(setId, offset + listed.length) } : {}) } : {}),
|
|
200
|
+
...(hasMore && !owner ? { paginationUnavailable: "A calling Agent identity is required to continue; run list_sessions through the host tool runtime." } : {}),
|
|
201
|
+
...(selected ? { workspaceId: selected.id, workspacePath: selected.path } : {}),
|
|
202
|
+
};
|
|
203
|
+
};
|
|
204
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ryuu-64/dsh-session-tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Let the agent start a new chat session, send a message to another one, or wait for it to finish.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,9 +32,9 @@
|
|
|
32
32
|
"client": {
|
|
33
33
|
"platform": "web",
|
|
34
34
|
"inject": [
|
|
35
|
-
"@deepseek-ai/dsh-client-runtime",
|
|
36
35
|
"@deepseek-ai/dsh-client-ui-slots",
|
|
37
|
-
"@deepseek-ai/dsh-client-ui-tool"
|
|
36
|
+
"@deepseek-ai/dsh-client-ui-tool",
|
|
37
|
+
"@deepseek-ai/dsh-client-ui-workspace"
|
|
38
38
|
]
|
|
39
39
|
}
|
|
40
40
|
},
|
|
@@ -44,13 +44,13 @@
|
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
46
|
"@deepseek-ai/cordis": "^4.0.2",
|
|
47
|
-
"@deepseek-ai/dsh-agent": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
|
|
48
|
-
"@deepseek-ai/dsh-agent-default-model": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
|
|
49
|
-
"@deepseek-ai/dsh-brand": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
|
|
50
|
-
"@deepseek-ai/dsh-llm": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
|
|
51
|
-
"@deepseek-ai/dsh-session-title": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
|
|
52
|
-
"@deepseek-ai/dsh-tools": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
|
|
53
|
-
"@deepseek-ai/dsh-workspace": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0",
|
|
47
|
+
"@deepseek-ai/dsh-agent": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
|
|
48
|
+
"@deepseek-ai/dsh-agent-default-model": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
|
|
49
|
+
"@deepseek-ai/dsh-brand": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
|
|
50
|
+
"@deepseek-ai/dsh-llm": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
|
|
51
|
+
"@deepseek-ai/dsh-session-title": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
|
|
52
|
+
"@deepseek-ai/dsh-tools": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
|
|
53
|
+
"@deepseek-ai/dsh-workspace": ">=0.1.5-rc.2 <0.1.6-0 || >=0.1.6-0 <0.2.0-0 || 0.2.0-rc.2",
|
|
54
54
|
"@deepseek-ai/schemastery": "^3.18.2",
|
|
55
55
|
"react": ">=18 <20"
|
|
56
56
|
},
|
|
@@ -58,5 +58,93 @@
|
|
|
58
58
|
"lib",
|
|
59
59
|
"cordis.patch.yml",
|
|
60
60
|
"README.md"
|
|
61
|
-
]
|
|
61
|
+
],
|
|
62
|
+
"engines": {
|
|
63
|
+
"node": "^22.19.0 || ^24.0.0"
|
|
64
|
+
},
|
|
65
|
+
"devDependencies": {
|
|
66
|
+
"@deepseek-ai/cordis": "4.0.4",
|
|
67
|
+
"@deepseek-ai/cordis-plugin-loader": "1.0.5",
|
|
68
|
+
"@deepseek-ai/dsh-agent": "0.2.0-rc.2",
|
|
69
|
+
"@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
|
|
70
|
+
"@deepseek-ai/dsh-agent-loop": "0.2.0-rc.2",
|
|
71
|
+
"@deepseek-ai/dsh-api-session-controller": "0.2.0-rc.2",
|
|
72
|
+
"@deepseek-ai/dsh-brand": "0.2.0-rc.2",
|
|
73
|
+
"@deepseek-ai/dsh-client-store": "0.2.0-rc.2",
|
|
74
|
+
"@deepseek-ai/dsh-client-ui-layout": "0.2.0-rc.2",
|
|
75
|
+
"@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
|
|
76
|
+
"@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
|
|
77
|
+
"@deepseek-ai/dsh-client-ui-workspace": "0.2.0-rc.2",
|
|
78
|
+
"@deepseek-ai/dsh-llm": "0.2.0-rc.2",
|
|
79
|
+
"@deepseek-ai/dsh-sandbox-policy": "0.2.0-rc.2",
|
|
80
|
+
"@deepseek-ai/dsh-session": "0.2.0-rc.2",
|
|
81
|
+
"@deepseek-ai/dsh-session-persistence": "0.2.0-rc.2",
|
|
82
|
+
"@deepseek-ai/dsh-session-persistence-jsonl": "0.2.0-rc.2",
|
|
83
|
+
"@deepseek-ai/dsh-session-projection": "0.2.0-rc.2",
|
|
84
|
+
"@deepseek-ai/dsh-session-query": "0.2.0-rc.2",
|
|
85
|
+
"@deepseek-ai/dsh-session-title": "0.2.0-rc.2",
|
|
86
|
+
"@deepseek-ai/dsh-session-title-first-prompt-llm": "0.2.0-rc.2",
|
|
87
|
+
"@deepseek-ai/dsh-session-title-llm": "0.2.0-rc.2",
|
|
88
|
+
"@deepseek-ai/dsh-storage": "0.2.0-rc.2",
|
|
89
|
+
"@deepseek-ai/dsh-storage-domain": "0.2.0-rc.2",
|
|
90
|
+
"@deepseek-ai/dsh-storage-json": "0.2.0-rc.2",
|
|
91
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
|
|
92
|
+
"@deepseek-ai/dsh-tools": "0.2.0-rc.2",
|
|
93
|
+
"@deepseek-ai/dsh-user-approval": "0.2.0-rc.2",
|
|
94
|
+
"@deepseek-ai/dsh-workspace": "0.2.0-rc.2",
|
|
95
|
+
"@deepseek-ai/schemastery": "3.18.4",
|
|
96
|
+
"immer": "10.1.1",
|
|
97
|
+
"react": "18.3.1",
|
|
98
|
+
"react-dom": "18.3.1",
|
|
99
|
+
"yaml": "2.9.0",
|
|
100
|
+
"zustand": "4.4.7"
|
|
101
|
+
},
|
|
102
|
+
"overrides": {
|
|
103
|
+
"@deepseek-ai/dsh-scope": "0.2.0-rc.2",
|
|
104
|
+
"@deepseek-ai/dsh-invariants": "0.2.0-rc.2",
|
|
105
|
+
"@deepseek-ai/dsh-util-values": "0.2.0-rc.2",
|
|
106
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
|
|
107
|
+
"@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
|
|
108
|
+
"@deepseek-ai/dsh-session-projection": "0.2.0-rc.2",
|
|
109
|
+
"@deepseek-ai/dsh-brand": "0.2.0-rc.2",
|
|
110
|
+
"@deepseek-ai/dsh-timeout": "0.2.0-rc.2",
|
|
111
|
+
"@deepseek-ai/dsh-util-crypto": "0.2.0-rc.2",
|
|
112
|
+
"@deepseek-ai/dsh-session": "0.2.0-rc.2",
|
|
113
|
+
"@deepseek-ai/dsh-llm": "0.2.0-rc.2",
|
|
114
|
+
"@deepseek-ai/dsh-agent": "0.2.0-rc.2",
|
|
115
|
+
"@deepseek-ai/dsh-tools": "0.2.0-rc.2",
|
|
116
|
+
"@deepseek-ai/dsh-workspace": "0.2.0-rc.2",
|
|
117
|
+
"@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
|
|
118
|
+
"@deepseek-ai/dsh-session-title": "0.2.0-rc.2",
|
|
119
|
+
"@deepseek-ai/dsh-agent-loop": "0.2.0-rc.2",
|
|
120
|
+
"@deepseek-ai/dsh-session-persistence": "0.2.0-rc.2",
|
|
121
|
+
"@deepseek-ai/dsh-code-runtime": "0.2.0-rc.2",
|
|
122
|
+
"@deepseek-ai/dsh-user-approval": "0.2.0-rc.2",
|
|
123
|
+
"@deepseek-ai/dsh-storage": "0.2.0-rc.2",
|
|
124
|
+
"@deepseek-ai/dsh-settings": "0.2.0-rc.2",
|
|
125
|
+
"@deepseek-ai/dsh-storage-domain": "0.2.0-rc.2",
|
|
126
|
+
"@deepseek-ai/dsh-session-persistence-jsonl": "0.2.0-rc.2",
|
|
127
|
+
"@deepseek-ai/dsh-session-format-v2-to-v3": "0.2.0-rc.2",
|
|
128
|
+
"@deepseek-ai/dsh-session-format-v1-to-v2": "0.2.0-rc.2",
|
|
129
|
+
"@deepseek-ai/dsh-session-format-v0-to-v1": "0.2.0-rc.2",
|
|
130
|
+
"@deepseek-ai/dsh-session-format": "0.2.0-rc.2",
|
|
131
|
+
"@deepseek-ai/dsh-session-format-catalog": "0.2.0-rc.2",
|
|
132
|
+
"@deepseek-ai/dsh-storage-json": "0.2.0-rc.2",
|
|
133
|
+
"@deepseek-ai/dsh-sandbox-policy": "0.2.0-rc.2",
|
|
134
|
+
"@deepseek-ai/dsh-sandbox": "0.2.0-rc.2",
|
|
135
|
+
"@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
|
|
136
|
+
"@deepseek-ai/dsh-session-title-first-prompt-llm": "0.2.0-rc.2",
|
|
137
|
+
"@deepseek-ai/dsh-session-title-llm": "0.2.0-rc.2",
|
|
138
|
+
"@deepseek-ai/dsh-session-query": "0.2.0-rc.2",
|
|
139
|
+
"@deepseek-ai/dsh-tool-todo": "0.2.0-rc.2",
|
|
140
|
+
"@deepseek-ai/dsh-session-projection-cache": "0.2.0-rc.2",
|
|
141
|
+
"@deepseek-ai/dsh-client-ui-workspace": "0.2.0-rc.2",
|
|
142
|
+
"@deepseek-ai/dsh-client-store": "0.2.0-rc.2",
|
|
143
|
+
"@deepseek-ai/dsh-api-session-controller": "0.2.0-rc.2",
|
|
144
|
+
"@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
|
|
145
|
+
"@deepseek-ai/dsh-client-ui-layout": "0.2.0-rc.2"
|
|
146
|
+
},
|
|
147
|
+
"dependencies": {
|
|
148
|
+
"zod": "4.6.5"
|
|
149
|
+
}
|
|
62
150
|
}
|