@ryuu-64/dsh-session-tools 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,123 @@
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 active observations, shared by overlapping calls to this tool instance. */
25
+ function readSlots() {
26
+ let active = 0;
27
+ const waiting = [];
28
+ return async (read, signal) => {
29
+ signal?.throwIfAborted();
30
+ if (active < 4) active++;
31
+ else await new Promise((resolve, reject) => {
32
+ const entry = { resolve: () => { signal?.removeEventListener("abort", abort); resolve(); } };
33
+ const abort = () => {
34
+ const index = waiting.indexOf(entry);
35
+ if (index >= 0) waiting.splice(index, 1);
36
+ reject(signal.reason);
37
+ };
38
+ waiting.push(entry);
39
+ signal?.addEventListener("abort", abort, { once: true });
40
+ });
41
+ try {
42
+ signal?.throwIfAborted();
43
+ return await read();
44
+ } finally {
45
+ const next = waiting.shift();
46
+ if (next) next.resolve();
47
+ else active--;
48
+ }
49
+ };
50
+ }
51
+
52
+ const identity = service => service?.[symbols.original] ?? service;
53
+
54
+ /** Cache only the derived number, never a log, a read handle, or an Agent. */
55
+ export function createActivitySorter(ctx) {
56
+ const cache = new Map();
57
+ const liveCache = new WeakMap();
58
+ const inSlot = readSlots();
59
+ async function activity(record, signal) {
60
+ const id = String(record.header.id);
61
+ const live = ctx.get("sessions")?.get(id) ?? ctx.agents.get(id)?.session;
62
+ if (typeof live?.snapshotEvents === "function") {
63
+ const events = live.snapshotEvents();
64
+ const source = identity(live);
65
+ const previous = liveCache.get(source);
66
+ if (previous?.version === events.length) return previous.time;
67
+ const time = conversationActivity(events, live.header.createdAt, live.inheritedEventCount);
68
+ liveCache.set(source, { version: events.length, time });
69
+ return time;
70
+ }
71
+ const persistence = ctx.get("sessionPersistence");
72
+ if (persistence !== undefined) {
73
+ const source = identity(persistence);
74
+ // Revisions are comparable only for the same service instance and id.
75
+ const version = (await persistence.stat?.(id, { signal }))?.revision;
76
+ signal?.throwIfAborted();
77
+ const previous = cache.get(id);
78
+ if (version !== undefined && previous?.source === source && previous.version === version) return previous.time;
79
+ const reader = await persistence.open(id, "read", { signal });
80
+ let time;
81
+ try {
82
+ signal?.throwIfAborted();
83
+ const { events } = await reader.read(0, undefined, { signal });
84
+ signal?.throwIfAborted();
85
+ time = conversationActivity(events, reader.header.createdAt, reader.inheritedEventCount);
86
+ } finally {
87
+ await reader.close();
88
+ }
89
+ if (version !== undefined) cache.set(id, { source, version, time });
90
+ return time;
91
+ }
92
+ // Query-only hosts have no revision token, so never reuse a cold result.
93
+ const log = await ctx.get("sessionQuery").readSession(id);
94
+ signal?.throwIfAborted();
95
+ return conversationActivity(log.events, record.header.createdAt, log.inheritedEventCount);
96
+ }
97
+ return async (records, signal) => {
98
+ signal?.throwIfAborted();
99
+ const ids = new Set(records.map(record => String(record.header.id)));
100
+ for (const id of cache.keys()) if (!ids.has(id)) cache.delete(id);
101
+ // Wait for every observation to close, including after an error/abort.
102
+ const ordered = [];
103
+ let next = 0;
104
+ let failed = false;
105
+ const worker = async () => {
106
+ try {
107
+ while (!failed && next < records.length) {
108
+ const index = next++;
109
+ const record = records[index];
110
+ const time = await inSlot(() => activity(record, signal), signal);
111
+ ordered.push({ record, index, time });
112
+ }
113
+ } catch (error) { failed = true; throw error; }
114
+ };
115
+ const results = await Promise.allSettled(Array.from({ length: Math.min(4, records.length) }, worker));
116
+ const failure = results.find(result => result.status === "rejected");
117
+ if (failure) throw failure.reason;
118
+ signal?.throwIfAborted();
119
+ return ordered
120
+ .sort((a, b) => b.time - a.time || a.index - b.index)
121
+ .map(({ record }) => record);
122
+ };
123
+ }
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "@ryuu-64/dsh-session-tools",
3
- "version": "0.5.3",
3
+ "version": "0.6.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",
7
+ "scripts": {
8
+ "test": "node --test \"test/**/*.test.mjs\"",
9
+ "check": "node --check lib/index.js && node --check lib/client.js && npm test"
10
+ },
7
11
  "keywords": [
8
12
  "deepseek-harness",
9
13
  "dsh",
@@ -54,5 +58,81 @@
54
58
  "lib",
55
59
  "cordis.patch.yml",
56
60
  "README.md"
57
- ]
61
+ ],
62
+ "engines": {
63
+ "node": "^22.19.0 || ^24.0.0"
64
+ },
65
+ "devDependencies": {
66
+ "@deepseek-ai/cordis": "4.0.2",
67
+ "@deepseek-ai/dsh-agent": "0.1.5-rc.2",
68
+ "@deepseek-ai/dsh-agent-default-model": "0.1.5-rc.2",
69
+ "@deepseek-ai/dsh-brand": "0.1.5-rc.2",
70
+ "@deepseek-ai/dsh-llm": "0.1.5-rc.2",
71
+ "@deepseek-ai/dsh-session-title": "0.1.5-rc.2",
72
+ "@deepseek-ai/dsh-tools": "0.1.5-rc.2",
73
+ "@deepseek-ai/dsh-workspace": "0.1.5-rc.2",
74
+ "@deepseek-ai/schemastery": "3.18.2",
75
+ "react": "19.2.0",
76
+ "@deepseek-ai/dsh-session": "0.1.5-rc.2",
77
+ "@deepseek-ai/dsh-agent-loop": "0.1.5-rc.2",
78
+ "@deepseek-ai/cordis-plugin-loader": "1.0.3",
79
+ "@deepseek-ai/dsh-session-persistence": "0.1.5-rc.2",
80
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.1.5-rc.2",
81
+ "@deepseek-ai/dsh-storage-json": "0.1.5-rc.2",
82
+ "@deepseek-ai/dsh-sandbox-policy": "0.1.5-rc.2",
83
+ "@deepseek-ai/dsh-user-approval": "0.1.5-rc.2",
84
+ "@deepseek-ai/dsh-system-prompt": "0.1.5-rc.2",
85
+ "@deepseek-ai/dsh-session-projection": "0.1.5-rc.2",
86
+ "@deepseek-ai/dsh-storage-domain": "0.1.5-rc.2",
87
+ "@deepseek-ai/dsh-storage": "0.1.5-rc.2",
88
+ "yaml": "2.9.0",
89
+ "@deepseek-ai/dsh-client-ui-slots": "0.1.5-rc.2",
90
+ "react-dom": "19.2.0",
91
+ "@deepseek-ai/dsh-session-title-first-prompt-llm": "0.1.5-rc.2",
92
+ "@deepseek-ai/dsh-session-title-llm": "0.1.5-rc.2",
93
+ "@deepseek-ai/dsh-session-query": "0.1.5-rc.2"
94
+ },
95
+ "overrides": {
96
+ "@deepseek-ai/dsh-scope": "0.1.5-rc.2",
97
+ "@deepseek-ai/dsh-invariants": "0.1.5-rc.2",
98
+ "@deepseek-ai/dsh-util-values": "0.1.5-rc.2",
99
+ "@deepseek-ai/dsh-system-prompt": "0.1.5-rc.2",
100
+ "@deepseek-ai/dsh-typert-protocol": "0.1.5-rc.2",
101
+ "@deepseek-ai/dsh-session-projection": "0.1.5-rc.2",
102
+ "@deepseek-ai/dsh-brand": "0.1.5-rc.2",
103
+ "@deepseek-ai/dsh-timeout": "0.1.5-rc.2",
104
+ "@deepseek-ai/dsh-util-crypto": "0.1.5-rc.2",
105
+ "@deepseek-ai/dsh-session": "0.1.5-rc.2",
106
+ "@deepseek-ai/dsh-llm": "0.1.5-rc.2",
107
+ "@deepseek-ai/dsh-agent": "0.1.5-rc.2",
108
+ "@deepseek-ai/dsh-tools": "0.1.5-rc.2",
109
+ "@deepseek-ai/dsh-workspace": "0.1.5-rc.2",
110
+ "@deepseek-ai/dsh-agent-default-model": "0.1.5-rc.2",
111
+ "@deepseek-ai/dsh-session-title": "0.1.5-rc.2",
112
+ "@deepseek-ai/dsh-agent-loop": "0.1.5-rc.2",
113
+ "@deepseek-ai/dsh-session-persistence": "0.1.5-rc.2",
114
+ "@deepseek-ai/dsh-code-runtime": "0.1.5-rc.2",
115
+ "@deepseek-ai/dsh-user-approval": "0.1.5-rc.2",
116
+ "@deepseek-ai/dsh-storage": "0.1.5-rc.2",
117
+ "@deepseek-ai/dsh-settings": "0.1.5-rc.2",
118
+ "@deepseek-ai/dsh-storage-domain": "0.1.5-rc.2",
119
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.1.5-rc.2",
120
+ "@deepseek-ai/dsh-session-format-v2-to-v3": "0.1.5-rc.2",
121
+ "@deepseek-ai/dsh-session-format-v1-to-v2": "0.1.5-rc.2",
122
+ "@deepseek-ai/dsh-session-format-v0-to-v1": "0.1.5-rc.2",
123
+ "@deepseek-ai/dsh-session-format": "0.1.5-rc.2",
124
+ "@deepseek-ai/dsh-session-format-catalog": "0.1.5-rc.2",
125
+ "@deepseek-ai/dsh-storage-json": "0.1.5-rc.2",
126
+ "@deepseek-ai/dsh-sandbox-policy": "0.1.5-rc.2",
127
+ "@deepseek-ai/dsh-sandbox": "0.1.5-rc.2",
128
+ "@deepseek-ai/dsh-client-ui-slots": "0.1.5-rc.2",
129
+ "@deepseek-ai/dsh-session-title-first-prompt-llm": "0.1.5-rc.2",
130
+ "@deepseek-ai/dsh-session-title-llm": "0.1.5-rc.2",
131
+ "@deepseek-ai/dsh-session-query": "0.1.5-rc.2",
132
+ "@deepseek-ai/dsh-tool-todo": "0.1.5-rc.2",
133
+ "@deepseek-ai/dsh-session-projection-cache": "0.1.5-rc.2"
134
+ },
135
+ "dependencies": {
136
+ "zod": "4.6.5"
137
+ }
58
138
  }