@ryuu-64/dsh-session-tools 0.8.0 → 0.8.1
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/LICENSE +21 -21
- package/README.md +21 -67
- package/README.zh-CN.md +39 -0
- package/cordis.patch.yml +4 -4
- package/lib/client.js +623 -528
- package/lib/communication-permissions.js +144 -101
- package/lib/communication-remote.js +75 -64
- package/lib/index.js +906 -894
- package/lib/message-receipts.js +156 -121
- package/lib/session-activity.js +135 -135
- package/lib/session-discovery.js +213 -213
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +27 -15
package/lib/message-receipts.js
CHANGED
|
@@ -1,121 +1,156 @@
|
|
|
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
|
-
/**
|
|
29
|
-
function
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
+
/** Keep an optional reader only while its owning Cordis scope is active. */
|
|
29
|
+
export function createReceiptProjectionReader(ctx) {
|
|
30
|
+
let reader;
|
|
31
|
+
ctx.inject?.(['sessionProjections'], scope => {
|
|
32
|
+
scope.effect(() => {
|
|
33
|
+
let active = true;
|
|
34
|
+
let ownedReader;
|
|
35
|
+
const register = async () => {
|
|
36
|
+
try {
|
|
37
|
+
const projections = scope.sessionProjections;
|
|
38
|
+
const handle = await projections.register(receiptProjection);
|
|
39
|
+
if (!active) return;
|
|
40
|
+
if (typeof handle?.stateOf === 'function') ownedReader = session => handle.stateOf(session);
|
|
41
|
+
else if (typeof handle === 'function') {
|
|
42
|
+
// The rc.2 registration is a synchronous disposer with no reader.
|
|
43
|
+
ownedReader = session => projections.stateOf(session, receiptProjectionKey);
|
|
44
|
+
}
|
|
45
|
+
reader = ownedReader;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (active) scope.logger.warn('Could not register the session receipt projection: %s', String(error));
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
void register();
|
|
51
|
+
return () => {
|
|
52
|
+
// The registry owns registration disposal on this same fiber.
|
|
53
|
+
active = false;
|
|
54
|
+
if (reader === ownedReader) reader = undefined;
|
|
55
|
+
};
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
return session => {
|
|
59
|
+
try { return reader?.(session); } catch { return undefined; }
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Pure, JSON-only projection. Invalid/incomplete logs fail attribution closed. */
|
|
64
|
+
function foldReceiptEvent(previous, event) {
|
|
65
|
+
if (!previous.valid) return previous;
|
|
66
|
+
const state = { ...previous, seq: event.seq };
|
|
67
|
+
const invalid = () => ({ ...state, valid: false });
|
|
68
|
+
if (!Number.isSafeInteger(event.seq) || event.seq !== previous.seq + 1) return invalid();
|
|
69
|
+
const data = event.data ?? {};
|
|
70
|
+
if (event.type === 'turn/start') {
|
|
71
|
+
if (state.openTurn !== null || !Number.isSafeInteger(data.turn) || data.turn <= 0 || Object.hasOwn(state.turns, data.turn)) return invalid();
|
|
72
|
+
return { ...state, openTurn: data.turn };
|
|
73
|
+
}
|
|
74
|
+
if (event.type === 'turn/end') {
|
|
75
|
+
if (state.openTurn !== data.turn || typeof data.reason?.kind !== 'string') return invalid();
|
|
76
|
+
return { ...state, openTurn: null, turns: { ...state.turns, [data.turn]: data.reason.kind } };
|
|
77
|
+
}
|
|
78
|
+
if (event.type === 'agent/inbox/spliced') {
|
|
79
|
+
const key = data.target === 'next-turn' ? 'nextTurn' : data.target === 'next-step' ? 'nextStep' : undefined;
|
|
80
|
+
if (!key) return invalid();
|
|
81
|
+
const list = state[key], count = data.removedCount ?? 0;
|
|
82
|
+
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();
|
|
83
|
+
if (data.outcome !== undefined && data.outcome !== 'canceled') return invalid();
|
|
84
|
+
const inserted = data.inserted.map(message => message?.id);
|
|
85
|
+
if (inserted.some(id => typeof id !== 'string' || id === '')) return invalid();
|
|
86
|
+
const removed = list.slice(data.start, data.start + count);
|
|
87
|
+
const next = list.toSpliced(data.start, count, ...inserted);
|
|
88
|
+
const pending = [...next, ...state[key === 'nextTurn' ? 'nextStep' : 'nextTurn']];
|
|
89
|
+
if (new Set(pending).size !== pending.length) return invalid();
|
|
90
|
+
const messages = { ...state.messages };
|
|
91
|
+
for (const id of removed) {
|
|
92
|
+
// Public claim() uses a pure deletion inside the already-open turn;
|
|
93
|
+
// ordinary remove/replace/clear logs outcome:canceled (discarded).
|
|
94
|
+
if (data.outcome === undefined && (state.openTurn === null || inserted.length !== 0)) return invalid();
|
|
95
|
+
messages[id] = { ...messages[id], state: data.outcome === 'canceled' ? 'discarded' : 'delivered', turn: data.outcome === 'canceled' ? null : state.openTurn };
|
|
96
|
+
}
|
|
97
|
+
for (const id of inserted) {
|
|
98
|
+
messages[id] = { state: 'queued', turn: null, admitted: false, ambiguous: Object.hasOwn(messages, id), inherited: event.seq < state.inheritedEventCount };
|
|
99
|
+
}
|
|
100
|
+
return { ...state, [key]: next, messages };
|
|
101
|
+
}
|
|
102
|
+
if (event.type === 'user/message') {
|
|
103
|
+
const message = state.messages[data.id];
|
|
104
|
+
if (!Object.hasOwn(state.messages, data.id)) return state;
|
|
105
|
+
if (message.state !== 'delivered' || message.turn !== state.openTurn || message.admitted) {
|
|
106
|
+
return { ...state, messages: { ...state.messages, [data.id]: { ...message, ambiguous: true } } };
|
|
107
|
+
}
|
|
108
|
+
return { ...state, messages: { ...state.messages, [data.id]: { ...message, admitted: true } } };
|
|
109
|
+
}
|
|
110
|
+
return state;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function foldReceipts(events, inheritedEventCount = 0) {
|
|
114
|
+
return events.reduce(foldReceiptEvent, receiptProjection.init(undefined, inheritedEventCount));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Same output selection as rc.2 AssistantOutputFold, restricted to one turn. */
|
|
118
|
+
export function turnOutput(events, turn) {
|
|
119
|
+
let message;
|
|
120
|
+
const partial = [];
|
|
121
|
+
let inside = false;
|
|
122
|
+
for (const event of events) {
|
|
123
|
+
if (event.type === 'turn/start' && event.data.turn === turn) inside = true;
|
|
124
|
+
if (event.type === 'turn/end' && event.data.turn === turn) break;
|
|
125
|
+
if (!inside || event.data?.turn !== turn || !['assistant/message', 'assistant/attempt'].includes(event.type)) continue;
|
|
126
|
+
if (event.type === 'assistant/message' && event.data.message?.content?.length > 0) message = event.data.message.content;
|
|
127
|
+
const stream = event.data.stream ?? [];
|
|
128
|
+
// Public stream readers trust types; validate persisted records first.
|
|
129
|
+
expandAssistantStream(stream);
|
|
130
|
+
partial.push(joinAssistantStreamText(stream));
|
|
131
|
+
}
|
|
132
|
+
const text = message === undefined ? partial.join('') : message.filter(block => block.type === 'text').map(block => block.text).join('');
|
|
133
|
+
return text.trim() === '' ? undefined : text;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function messageReceipt(state, messageId, events) {
|
|
137
|
+
const unknown = note => ({ messageStatus: 'unknown', completed: false, attributionNote: note });
|
|
138
|
+
if (!state.valid) return unknown('The event log is incomplete or cannot reliably identify this message.');
|
|
139
|
+
if (!Object.hasOwn(state.messages, messageId)) return unknown('No durable receipt for this message was found.');
|
|
140
|
+
const message = state.messages[messageId];
|
|
141
|
+
if (message.ambiguous || message.inherited) return unknown('This identity is reused or belongs to inherited history; its result cannot be attributed.');
|
|
142
|
+
const base = { messageStatus: message.state, completed: false, ...(message.turn === null ? {} : { turn: message.turn }) };
|
|
143
|
+
if (message.turn === null) return base;
|
|
144
|
+
const kind = state.turns[message.turn];
|
|
145
|
+
if (kind === undefined) return base;
|
|
146
|
+
const ended = { ...base, turnEndKind: kind };
|
|
147
|
+
if (kind === 'completed' && !message.admitted) return { ...ended, ...unknown('The turn ended without admitting this message to the model.') };
|
|
148
|
+
const messageStatus = { completed: 'turnCompleted', aborted: 'cancelled', blocked: 'blocked', error: 'failed', interrupted: 'interrupted', 'max-tokens': 'incomplete' }[kind] ?? 'unknown';
|
|
149
|
+
if (messageStatus !== 'turnCompleted') return { ...ended, messageStatus };
|
|
150
|
+
try {
|
|
151
|
+
const output = turnOutput(events, message.turn);
|
|
152
|
+
return { ...ended, messageStatus, completed: true, ...(output === undefined ? {} : { output }) };
|
|
153
|
+
} catch {
|
|
154
|
+
return { ...ended, ...unknown('The recorded output could not be decoded reliably.') };
|
|
155
|
+
}
|
|
156
|
+
}
|
package/lib/session-activity.js
CHANGED
|
@@ -1,135 +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
|
-
}
|
|
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
|
+
}
|