dsh-ws-recency 0.14.0 → 0.16.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.
Files changed (4) hide show
  1. package/README.md +34 -8
  2. package/client.js +2647 -2242
  3. package/index.js +270 -2
  4. package/package.json +2 -2
package/index.js CHANGED
@@ -17,6 +17,11 @@
17
17
  * Nothing is erased irreversibly: the log directory is renamed, so restoring is
18
18
  * a move back. The route only answers loopback origins and only accepts POST.
19
19
  *
20
+ * The same module owns the other kind of put-away: the Host's archive set. An
21
+ * archived Session keeps its slot and its log but is hidden from every grouping
22
+ * surface, so the trash panel lists it too and can unarchive it, delete it into
23
+ * the trash above, or erase it for good.
24
+ *
20
25
  * @module dsh-ws-recency
21
26
  */
22
27
  import { mkdir, readFile, readdir, rename, rm, stat as statPath, writeFile } from "node:fs/promises";
@@ -26,7 +31,7 @@ import { dirname, join } from "node:path";
26
31
  export const name = "ws-recency";
27
32
 
28
33
  /** Version marker reported by the health route. */
29
- export const HOST_VERSION = "0.10.1";
34
+ export const HOST_VERSION = "0.16.0";
30
35
 
31
36
  /**
32
37
  * Exact routes the client half calls. Registered on the bare web server, so they
@@ -928,7 +933,250 @@ export async function purgeTrashEntry(name) {
928
933
  return { ok: true };
929
934
  }
930
935
 
931
- /** POST { action, name } -> list, restore or purge the plugin's trash. */
936
+ /* ------------------------------------------------------------------------- *
937
+ * Archived sessions
938
+ *
939
+ * The Host's archive is nothing but a flag in the registry's
940
+ * `archivedSessionIds`: the Session keeps its slot in the Workspace that owns it
941
+ * and its log stays under `sessions/`, yet every grouping surface hides it. That
942
+ * makes "archived" a second kind of put-away that nothing manages - only DSH's
943
+ * own view filter can show it again. The trash panel lists it next to the trash
944
+ * so both kinds of "put away" live in one place: unarchive (back into its old
945
+ * slot), delete into the plugin's trash (recoverable), or delete for good.
946
+ * ------------------------------------------------------------------------- */
947
+
948
+ /** The registry's durable archive set; a Host without one has none. */
949
+ function archivedSessionIds(ctx) {
950
+ try {
951
+ const ids = ctx.workspaceRegistry?.archivedSessionIds;
952
+ return Array.isArray(ids) ? ids.slice() : [];
953
+ } catch {
954
+ return [];
955
+ }
956
+ }
957
+
958
+ /** One session's projection-cache record: a listing hint, never authority. */
959
+ function cachedCheckpoint(ctx, sessionId) {
960
+ try {
961
+ const domain = ctx.get("storageDomain");
962
+ const table = domain !== undefined && domain !== null && typeof domain.get === "function"
963
+ ? domain.get("session_projcache")?.table("sessions")
964
+ : undefined;
965
+ const record = table !== undefined && table !== null && typeof table.get === "function" ? table.get(sessionId) : undefined;
966
+ return record !== undefined && record !== null && typeof record === "object" ? record : undefined;
967
+ } catch {
968
+ return undefined;
969
+ }
970
+ }
971
+
972
+ /** A checkpoint row's `val`, whichever fold unit it belongs to. */
973
+ function checkpointValue(record, key) {
974
+ const row = record?.rows?.[key];
975
+ return row !== null && typeof row === "object" && "val" in row ? row.val : undefined;
976
+ }
977
+
978
+ /**
979
+ * Title fallback for a session the projection cache has no record for.
980
+ *
981
+ * A title is written right after the first prompt, so the first page of the log
982
+ * is enough - and reading one page is far cheaper than folding the whole Log.
983
+ */
984
+ async function titleFromLog(ctx, sessionId) {
985
+ let handle;
986
+ try {
987
+ handle = await ctx.sessionPersistence.open(sessionId, "read");
988
+ } catch {
989
+ return "";
990
+ }
991
+ try {
992
+ const slice = await handle.read(0, 60);
993
+ const events = slice !== null && slice !== undefined && Array.isArray(slice.events) ? slice.events : [];
994
+ for (const event of events) {
995
+ if (event?.type !== "session/title") continue;
996
+ const title = typeof event.data === "string" ? event.data : event.data?.title;
997
+ if (typeof title === "string" && title.trim() !== "") return title.trim();
998
+ }
999
+ for (const event of events) {
1000
+ if (event?.type !== "user/message") continue;
1001
+ const line = blockText(event.data?.content).split("\n")[0].trim();
1002
+ if (line !== "") return line.slice(0, 120);
1003
+ }
1004
+ return "";
1005
+ } catch {
1006
+ return "";
1007
+ } finally {
1008
+ try {
1009
+ if (typeof handle.close === "function") await handle.close();
1010
+ } catch {
1011
+ /* closing is best effort */
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ /** Whether a workspace lists the session in the stored table rather than the filtered view. */
1017
+ function listedBy(workspace, raw, sessionId) {
1018
+ const record = raw === null ? undefined : raw.get(workspace.id);
1019
+ if (record !== undefined) return record.sessionIds.includes(sessionId);
1020
+ return Array.isArray(workspace.sessionIds) && workspace.sessionIds.includes(sessionId);
1021
+ }
1022
+
1023
+ /**
1024
+ * Every archived session, newest activity first.
1025
+ *
1026
+ * One persistence listing covers the stored headers (cwd, createdAt); the title
1027
+ * and the last prompt time come from the projection cache, which is far cheaper
1028
+ * than folding each log - and is only a display hint, so a stale title is fine.
1029
+ */
1030
+ export async function listArchivedSessions(ctx) {
1031
+ const ids = archivedSessionIds(ctx);
1032
+ if (ids.length === 0) return { ok: true, entries: [] };
1033
+
1034
+ const headers = new Map();
1035
+ const sizes = new Map();
1036
+ try {
1037
+ const snapshots = await ctx.sessionPersistence.list();
1038
+ for (const snapshot of Array.isArray(snapshots) ? snapshots : []) {
1039
+ const header = snapshot !== null && snapshot !== undefined ? snapshot.header : undefined;
1040
+ if (header === null || header === undefined || typeof header.id !== "string") continue;
1041
+ headers.set(header.id, header);
1042
+ if (typeof snapshot.sizeBytes === "number") sizes.set(header.id, snapshot.sizeBytes);
1043
+ }
1044
+ } catch {
1045
+ /* fall back to a stat per id below */
1046
+ }
1047
+
1048
+ const raw = await rawWorkspaceMembership();
1049
+ const workspaces = ctx.workspaceRegistry.list();
1050
+ const entries = [];
1051
+ for (const sessionId of ids) {
1052
+ let header = headers.get(sessionId);
1053
+ let sizeBytes = sizes.get(sessionId) ?? 0;
1054
+ if (header === undefined) {
1055
+ try {
1056
+ const stat = await ctx.sessionPersistence.stat(sessionId);
1057
+ header = stat !== undefined && stat !== null ? stat.header : undefined;
1058
+ sizeBytes = Number(stat?.sizeBytes) || 0;
1059
+ } catch {
1060
+ header = undefined;
1061
+ }
1062
+ }
1063
+
1064
+ const checkpoint = cachedCheckpoint(ctx, sessionId);
1065
+ let title = checkpointValue(checkpoint, "title");
1066
+ title = typeof title === "string" ? title.trim() : "";
1067
+ if (title === "") {
1068
+ /* The first prompt is what the sidebar itself falls back to. */
1069
+ const outline = checkpointValue(checkpoint, "turnOutline");
1070
+ const prompt = Array.isArray(outline?.turns) && outline.turns.length > 0 ? outline.turns[0]?.prompt : undefined;
1071
+ if (typeof prompt === "string") title = prompt.split("\n")[0].trim().slice(0, 120);
1072
+ }
1073
+ if (title === "" && typeof header?.title === "string") title = header.title.trim();
1074
+ /* Last resort: the cache may have no record for this session at all. */
1075
+ if (title === "") title = await titleFromLog(ctx, sessionId);
1076
+
1077
+ const listMeta = checkpointValue(checkpoint, "sessionListMetadata");
1078
+ let lastAt = typeof listMeta?.lastPromptAt === "number" ? listMeta.lastPromptAt : 0;
1079
+ if (lastAt === 0 && typeof header?.updatedAt === "number") lastAt = header.updatedAt;
1080
+ if (lastAt === 0 && typeof header?.createdAt === "number") lastAt = header.createdAt;
1081
+
1082
+ const cwd = typeof header?.cwd === "string" && header.cwd !== "" ? header.cwd : null;
1083
+ let workspace = workspaces.find((candidate) => listedBy(candidate, raw, sessionId));
1084
+ if (workspace === undefined && cwd !== null) workspace = workspaces.find((candidate) => candidate.path === cwd);
1085
+
1086
+ entries.push({
1087
+ sessionId,
1088
+ title,
1089
+ cwd,
1090
+ createdAt: typeof header?.createdAt === "number" ? header.createdAt : 0,
1091
+ lastAt,
1092
+ sizeBytes,
1093
+ blank: listMeta?.blank === true,
1094
+ workspaceId: workspace !== undefined ? workspace.id : null,
1095
+ workspacePath: workspace !== undefined ? workspace.path : null,
1096
+ /* Whether a Workspace still lists it: an unarchive without one has nowhere to show up. */
1097
+ listed: workspace !== undefined,
1098
+ });
1099
+ }
1100
+ entries.sort((a, b) => b.lastAt - a.lastAt || (a.sessionId < b.sessionId ? -1 : 1));
1101
+ return { ok: true, entries };
1102
+ }
1103
+
1104
+ /**
1105
+ * Put an archived session back.
1106
+ *
1107
+ * Unarchiving never touches workspace accounting, so the slot the session had is
1108
+ * normally enough. A session whose Workspace was deleted while it was archived
1109
+ * has nowhere to return to: attach it to a Workspace whose path matches its cwd,
1110
+ * and report that it could not be shown otherwise.
1111
+ */
1112
+ export async function restoreArchivedSession(ctx, sessionId) {
1113
+ if (!archivedSessionIds(ctx).includes(sessionId)) return { ok: false, error: "session is not archived" };
1114
+ try {
1115
+ await ctx.workspaceRegistry.unarchiveSession(sessionId);
1116
+ } catch (error) {
1117
+ return { ok: false, error: `could not unarchive: ${error instanceof Error ? error.message : String(error)}` };
1118
+ }
1119
+
1120
+ let cwd = null;
1121
+ let createdAt = 0;
1122
+ try {
1123
+ const stat = await ctx.sessionPersistence.stat(sessionId);
1124
+ const header = stat !== undefined && stat !== null ? stat.header : undefined;
1125
+ if (typeof header?.cwd === "string") cwd = header.cwd;
1126
+ if (typeof header?.createdAt === "number") createdAt = header.createdAt;
1127
+ } catch {
1128
+ /* the archive flag is already gone; membership follows below */
1129
+ }
1130
+
1131
+ const workspaces = ctx.workspaceRegistry.list();
1132
+ const raw = await rawWorkspaceMembership();
1133
+ let listed = workspaces.some((workspace) => listedBy(workspace, raw, sessionId));
1134
+ if (!listed && cwd !== null) {
1135
+ const owner = workspaces.find((workspace) => workspace.path === cwd);
1136
+ if (owner !== undefined) {
1137
+ try {
1138
+ await owner.attachSession(sessionId);
1139
+ listed = true;
1140
+ } catch {
1141
+ /* a stale header is refused; the log is untouched */
1142
+ }
1143
+ }
1144
+ }
1145
+
1146
+ await announceSession(ctx, sessionId);
1147
+ return { ok: true, sessionId, cwd, createdAt, listed };
1148
+ }
1149
+
1150
+ /**
1151
+ * Delete an archived session for good.
1152
+ *
1153
+ * The normal delete already unarchives, detaches and moves the log into the
1154
+ * plugin's trash - erasing it is then the trash's own purge, so the two paths
1155
+ * cannot drift apart.
1156
+ */
1157
+ export async function forgetArchivedSession(ctx, sessionId) {
1158
+ const result = await trashSession(ctx, sessionId);
1159
+ if (result.ok !== true) return result;
1160
+ let purged = false;
1161
+ if (typeof result.trash === "string" && result.trash !== "") {
1162
+ const name = result.trash.split(/[/\\]/).filter((part) => part !== "").pop();
1163
+ if (typeof name === "string" && name !== "") {
1164
+ try {
1165
+ purged = (await purgeTrashEntry(name)).ok === true;
1166
+ } catch {
1167
+ purged = false;
1168
+ }
1169
+ }
1170
+ }
1171
+ return { ok: true, sessionId, purged };
1172
+ }
1173
+
1174
+ /**
1175
+ * POST { action, name?, sessionId? } -> the plugin's trash and the archive set.
1176
+ *
1177
+ * `list`/`restore`/`purge` address trash entries by directory name; `archived`
1178
+ * lists the archive set, and `unarchive`/`forget`/`delete` address sessions by id.
1179
+ */
932
1180
  export async function handleTrashListRequest(ctx, req, res) {
933
1181
  if ((req.method ?? "POST").toUpperCase() !== "POST") {
934
1182
  sendJson(res, 405, { ok: false, error: "method not allowed" });
@@ -945,6 +1193,26 @@ export async function handleTrashListRequest(ctx, req, res) {
945
1193
  sendJson(res, 200, await listTrash());
946
1194
  return;
947
1195
  }
1196
+ if (action === "archived") {
1197
+ sendJson(res, 200, await listArchivedSessions(ctx));
1198
+ return;
1199
+ }
1200
+ if (action === "unarchive" || action === "forget" || action === "delete") {
1201
+ const sessionId = sessionIdFrom(req, body);
1202
+ if (sessionId === "") {
1203
+ sendJson(res, 400, { ok: false, error: "sessionId required" });
1204
+ return;
1205
+ }
1206
+ /* `delete` is the archived row's way into the recoverable trash; the other
1207
+ two either put the session back or erase it afterwards. */
1208
+ const result = action === "unarchive"
1209
+ ? await restoreArchivedSession(ctx, sessionId)
1210
+ : action === "forget"
1211
+ ? await forgetArchivedSession(ctx, sessionId)
1212
+ : await trashSession(ctx, sessionId);
1213
+ sendJson(res, result.ok ? 200 : 500, result);
1214
+ return;
1215
+ }
948
1216
  const name = body !== null && typeof body.name === "string" ? body.name.trim() : "";
949
1217
  if (name === "") {
950
1218
  sendJson(res, 400, { ok: false, error: "entry name required" });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-ws-recency",
3
- "version": "0.14.0",
4
- "description": "Sidebar session management for DeepSeek Harness: workspace groups sorted by latest activity, stale history folded, a global pinned section, follow-up marks, session delete into a recoverable trash, per-session token statistics split by tool, and moving a session to another workspace.",
3
+ "version": "0.16.0",
4
+ "description": "Sidebar session management for DeepSeek Harness: workspace groups sorted by latest activity, stale history folded, a global pinned section, follow-up marks, session delete into a recoverable trash, archived sessions managed from that same trash panel, per-session token statistics with an argument/result split and an option to count tool arguments as the agent's writing, and moving a session to another workspace.",
5
5
  "license": "MIT",
6
6
  "author": "chyxhtc",
7
7
  "repository": {