@240xu/dsh-message-ops 0.11.8 → 0.13.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.
@@ -10,133 +10,162 @@
10
10
  * This module deliberately has no dependency on the HTTP layer so the contract
11
11
  * can be tested with a temporary DSH_HOME and an in-memory storageDomain.
12
12
  */
13
- import fs from "node:fs";
14
- import os from "node:os";
15
- import path from "node:path";
16
- import { randomUUID } from "node:crypto";
17
- import { OpsError, isSessionId, sessionIdVariants, sessionsRoot, readSessionHeader } from "./session-file.js";
13
+ import fs from 'node:fs'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+ import { randomUUID } from 'node:crypto'
17
+ import { OpsError, isSessionId, sessionIdVariants, sessionsRoot, readSessionHeader } from './session-file.js'
18
18
 
19
- export const TRASH_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
20
- const TRASH_ID_RE = /^\d{10,}-[0-9a-f]{8}$/;
19
+ export const TRASH_RETENTION_MS = 7 * 24 * 60 * 60 * 1000
20
+ const TRASH_ID_RE = /^\d{10,}-[0-9a-f]{8}$/
21
21
 
22
22
  function dshHome() {
23
- return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
23
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
24
24
  }
25
25
 
26
26
  export function trashRoot() {
27
- return path.join(dshHome(), "trash", "session-ops");
27
+ return path.join(dshHome(), 'trash', 'session-ops')
28
28
  }
29
29
 
30
30
  function cloneJson(value) {
31
- try { return JSON.parse(JSON.stringify(value)); } catch { return null; }
31
+ try {
32
+ return JSON.parse(JSON.stringify(value))
33
+ } catch {
34
+ return null
35
+ }
32
36
  }
33
37
 
34
38
  function findAllSessionDirs(sessionId) {
35
- const root = sessionsRoot();
36
- const variants = sessionIdVariants(sessionId);
37
- let slugs = [];
38
- try { slugs = fs.readdirSync(root, { withFileTypes: true }); } catch { return []; }
39
- const found = [];
39
+ const root = sessionsRoot()
40
+ const variants = sessionIdVariants(sessionId)
41
+ let slugs = []
42
+ try {
43
+ slugs = fs.readdirSync(root, { withFileTypes: true })
44
+ } catch {
45
+ return []
46
+ }
47
+ const found = []
40
48
  for (const slug of slugs) {
41
- if (!slug.isDirectory()) continue;
49
+ if (!slug.isDirectory()) continue
42
50
  for (const variant of variants) {
43
- const dir = path.join(root, slug.name, variant);
51
+ const dir = path.join(root, slug.name, variant)
44
52
  try {
45
- if (fs.statSync(dir).isDirectory() && !found.some((x) => x.dir === dir)) {
46
- found.push({ dir, slug: slug.name, name: variant });
53
+ if (fs.statSync(dir).isDirectory() && !found.some(x => x.dir === dir)) {
54
+ found.push({ dir, slug: slug.name, name: variant })
47
55
  }
48
- } catch { /* keep scanning */ }
56
+ } catch {
57
+ /* keep scanning */
58
+ }
49
59
  }
50
60
  }
51
- return found;
61
+ return found
52
62
  }
53
63
 
54
64
  function storageDomain(ctx) {
55
- try { return ctx && typeof ctx.get === "function" ? ctx.get("storageDomain") : undefined; } catch { return undefined; }
65
+ try {
66
+ return ctx && typeof ctx.get === 'function' ? ctx.get('storageDomain') : undefined
67
+ } catch {
68
+ return undefined
69
+ }
56
70
  }
57
71
 
58
72
  function projectionTable(ctx) {
59
- const sd = storageDomain(ctx);
60
- const domain = sd && typeof sd.get === "function" ? sd.get("session_projcache") : undefined;
61
- if (!domain || typeof domain.table !== "function") return null;
62
- try { return domain.table("sessions"); } catch { return null; }
73
+ const sd = storageDomain(ctx)
74
+ const domain = sd && typeof sd.get === 'function' ? sd.get('session_projcache') : undefined
75
+ if (!domain || typeof domain.table !== 'function') return null
76
+ try {
77
+ return domain.table('sessions')
78
+ } catch {
79
+ return null
80
+ }
63
81
  }
64
82
 
65
83
  function workspaceDomain(ctx) {
66
- const sd = storageDomain(ctx);
67
- const domain = sd && typeof sd.get === "function" ? sd.get("workspace") : undefined;
68
- return domain && typeof domain.table === "function" ? domain : null;
84
+ const sd = storageDomain(ctx)
85
+ const domain = sd && typeof sd.get === 'function' ? sd.get('workspace') : undefined
86
+ return domain && typeof domain.table === 'function' ? domain : null
69
87
  }
70
88
 
71
89
  function titleOfRow(row) {
72
- const title = row && row.rows && row.rows.title;
73
- if (title && typeof title.val === "string" && title.val.trim()) return title.val.trim();
74
- return null;
90
+ const title = row && row.rows && row.rows.title
91
+ if (title && typeof title.val === 'string' && title.val.trim()) return title.val.trim()
92
+ return null
75
93
  }
76
94
 
77
95
  function headerTitle(dir) {
78
96
  try {
79
- const header = readSessionHeader(path.join(dir, fs.readdirSync(dir).find((f) => /^session(\.v[34])?\.jsonl\.zstd$/.test(f)) || ""));
80
- for (const key of ["title", "name", "displayTitle"]) {
81
- if (header && typeof header[key] === "string" && header[key].trim()) return header[key].trim();
97
+ const header = readSessionHeader(path.join(dir, fs.readdirSync(dir).find(f => /^session(\.v[34])?\.jsonl\.zstd$/.test(f)) || ''))
98
+ for (const key of ['title', 'name', 'displayTitle']) {
99
+ if (header && typeof header[key] === 'string' && header[key].trim()) return header[key].trim()
82
100
  }
83
- if (header && header.session && typeof header.session.title === "string" && header.session.title.trim()) {
84
- return header.session.title.trim();
101
+ if (header && header.session && typeof header.session.title === 'string' && header.session.title.trim()) {
102
+ return header.session.title.trim()
85
103
  }
86
- } catch { /* header unreadable: caller decides */ }
87
- return null;
104
+ } catch {
105
+ /* header unreadable: caller decides */
106
+ }
107
+ return null
88
108
  }
89
109
 
90
110
  /** Resolve the confirmation text shown by the delete dialog. Prefers the
91
111
  * projection-cache title; falls back to the log header; untitled sessions
92
112
  * confirm by their stable session id. */
93
113
  export function resolveSessionTitle(ctx, sessionId) {
94
- if (!isSessionId(sessionId)) return null;
95
- const meta = readMetadata(ctx, sessionId);
96
- const title = titleOfRow(meta.projRow);
97
- if (title) return title;
98
- const dirs = findAllSessionDirs(sessionId);
114
+ if (!isSessionId(sessionId)) return null
115
+ const meta = readMetadata(ctx, sessionId)
116
+ const title = titleOfRow(meta.projRow)
117
+ if (title) return title
118
+ const dirs = findAllSessionDirs(sessionId)
99
119
  if (dirs.length === 1) {
100
- const fromHeader = headerTitle(dirs[0].dir);
101
- if (fromHeader) return fromHeader;
120
+ const fromHeader = headerTitle(dirs[0].dir)
121
+ if (fromHeader) return fromHeader
102
122
  }
103
- return sessionId;
123
+ return sessionId
104
124
  }
105
125
 
106
126
  function readMetadata(ctx, sessionId) {
107
- const variants = sessionIdVariants(sessionId);
108
- const projRows = [];
109
- const table = projectionTable(ctx);
110
- if (table && typeof table.get === "function") {
127
+ const variants = sessionIdVariants(sessionId)
128
+ const projRows = []
129
+ const table = projectionTable(ctx)
130
+ if (table && typeof table.get === 'function') {
111
131
  for (const variant of variants) {
112
- let row;
113
- try { row = table.get(variant); } catch { row = undefined; }
132
+ let row
133
+ try {
134
+ row = table.get(variant)
135
+ } catch {
136
+ row = undefined
137
+ }
114
138
  if (row !== undefined) {
115
- const copy = cloneJson(row);
116
- if (copy) projRows.push({ key: variant, row: copy });
139
+ const copy = cloneJson(row)
140
+ if (copy) projRows.push({ key: variant, row: copy })
117
141
  }
118
142
  }
119
143
  }
120
144
 
121
- const workspaceIds = [];
122
- const archived = [];
123
- const pinned = [];
124
- const ws = workspaceDomain(ctx);
145
+ const workspaceIds = []
146
+ const archived = []
147
+ const pinned = []
148
+ const ws = workspaceDomain(ctx)
125
149
  if (ws) {
126
- if (typeof ws.table === "function") {
150
+ if (typeof ws.table === 'function') {
127
151
  try {
128
- for (const [wid, rec] of ws.table("workspaces").entries()) {
129
- if (rec && Array.isArray(rec.sessionIds) && rec.sessionIds.some((x) => variants.includes(x))) {
130
- workspaceIds.push(wid);
152
+ for (const [wid, rec] of ws.table('workspaces').entries()) {
153
+ if (rec && Array.isArray(rec.sessionIds) && rec.sessionIds.some(x => variants.includes(x))) {
154
+ workspaceIds.push(wid)
131
155
  }
132
156
  }
133
- } catch { /* unit absent */ }
157
+ } catch {
158
+ /* unit absent */
159
+ }
134
160
  }
135
161
  try {
136
- const state = ws.global && typeof ws.global.get === "function" ? ws.global.get() : null;
137
- if (state && Array.isArray(state.archivedSessionIds) && state.archivedSessionIds.some((x) => variants.includes(x))) archived.push(sessionId);
138
- if (state && Array.isArray(state.pinnedSessionIds) && state.pinnedSessionIds.some((x) => variants.includes(x))) pinned.push(sessionId);
139
- } catch { /* no global slot */ }
162
+ const state = ws.global && typeof ws.global.get === 'function' ? ws.global.get() : null
163
+ if (state && Array.isArray(state.archivedSessionIds) && state.archivedSessionIds.some(x => variants.includes(x)))
164
+ archived.push(sessionId)
165
+ if (state && Array.isArray(state.pinnedSessionIds) && state.pinnedSessionIds.some(x => variants.includes(x))) pinned.push(sessionId)
166
+ } catch {
167
+ /* no global slot */
168
+ }
140
169
  }
141
170
 
142
171
  return {
@@ -145,127 +174,156 @@ function readMetadata(ctx, sessionId) {
145
174
  workspaceIds,
146
175
  archived: archived.length > 0,
147
176
  pinned: pinned.length > 0,
148
- };
177
+ }
149
178
  }
150
179
 
151
180
  async function stripMetadata(ctx, sessionId, meta) {
152
- const variants = sessionIdVariants(sessionId);
153
- const table = projectionTable(ctx);
154
- if (table && typeof table.delete === "function") {
155
- const keys = new Set((meta.projRows || []).map((x) => x.key));
156
- for (const variant of variants) keys.add(variant);
181
+ const variants = sessionIdVariants(sessionId)
182
+ const table = projectionTable(ctx)
183
+ if (table && typeof table.delete === 'function') {
184
+ const keys = new Set((meta.projRows || []).map(x => x.key))
185
+ for (const variant of variants) keys.add(variant)
157
186
  for (const key of keys) {
158
187
  try {
159
- if (typeof table.get !== "function" || table.get(key) !== undefined) await table.delete(key);
160
- } catch { /* domain closed: the manifest still has the row */ }
188
+ if (typeof table.get !== 'function' || table.get(key) !== undefined) await table.delete(key)
189
+ } catch {
190
+ /* domain closed: the manifest still has the row */
191
+ }
161
192
  }
162
193
  }
163
194
 
164
- const ws = workspaceDomain(ctx);
165
- if (ws && typeof ws.table === "function") {
195
+ const ws = workspaceDomain(ctx)
196
+ if (ws && typeof ws.table === 'function') {
166
197
  try {
167
- const workspaces = ws.table("workspaces");
198
+ const workspaces = ws.table('workspaces')
168
199
  for (const [wid, rec] of workspaces.entries()) {
169
- if (!rec || !Array.isArray(rec.sessionIds)) continue;
170
- const next = rec.sessionIds.filter((x) => !variants.includes(x));
171
- if (next.length !== rec.sessionIds.length) await workspaces.put(wid, { ...rec, sessionIds: next });
200
+ if (!rec || !Array.isArray(rec.sessionIds)) continue
201
+ const next = rec.sessionIds.filter(x => !variants.includes(x))
202
+ if (next.length !== rec.sessionIds.length) await workspaces.put(wid, { ...rec, sessionIds: next })
172
203
  }
173
- } catch { /* unit absent */ }
204
+ } catch {
205
+ /* unit absent */
206
+ }
174
207
  }
175
208
  if (ws && ws.global) {
176
209
  try {
177
- const state = ws.global.get();
210
+ const state = ws.global.get()
178
211
  if (state && (Array.isArray(state.archivedSessionIds) || Array.isArray(state.pinnedSessionIds))) {
179
- const next = { ...state };
180
- if (Array.isArray(next.archivedSessionIds)) next.archivedSessionIds = next.archivedSessionIds.filter((x) => !variants.includes(x));
181
- if (Array.isArray(next.pinnedSessionIds)) next.pinnedSessionIds = next.pinnedSessionIds.filter((x) => !variants.includes(x));
182
- await ws.global.set(next);
212
+ const next = { ...state }
213
+ if (Array.isArray(next.archivedSessionIds)) next.archivedSessionIds = next.archivedSessionIds.filter(x => !variants.includes(x))
214
+ if (Array.isArray(next.pinnedSessionIds)) next.pinnedSessionIds = next.pinnedSessionIds.filter(x => !variants.includes(x))
215
+ await ws.global.set(next)
183
216
  }
184
- } catch { /* no global slot */ }
217
+ } catch {
218
+ /* no global slot */
219
+ }
185
220
  }
186
221
  }
187
222
 
188
223
  async function restoreMetadata(ctx, sessionId, meta) {
189
- const table = projectionTable(ctx);
190
- if (table && typeof table.put === "function") {
224
+ const table = projectionTable(ctx)
225
+ if (table && typeof table.put === 'function') {
191
226
  for (const item of meta.projRows || []) {
192
- try { await table.put(item.key, item.row); } catch { /* domain closed */ }
227
+ try {
228
+ await table.put(item.key, item.row)
229
+ } catch {
230
+ /* domain closed */
231
+ }
193
232
  }
194
233
  }
195
- const ws = workspaceDomain(ctx);
196
- if (ws && typeof ws.table === "function") {
234
+ const ws = workspaceDomain(ctx)
235
+ if (ws && typeof ws.table === 'function') {
197
236
  try {
198
- const workspaces = ws.table("workspaces");
237
+ const workspaces = ws.table('workspaces')
199
238
  for (const wid of meta.workspaceIds || []) {
200
- let rec = typeof workspaces.get === "function" ? workspaces.get(wid) : undefined;
201
- if (!rec && typeof workspaces.entries === "function") {
239
+ let rec = typeof workspaces.get === 'function' ? workspaces.get(wid) : undefined
240
+ if (!rec && typeof workspaces.entries === 'function') {
202
241
  for (const [key, value] of workspaces.entries()) {
203
- if (key === wid) { rec = value; break; }
242
+ if (key === wid) {
243
+ rec = value
244
+ break
245
+ }
204
246
  }
205
247
  }
206
- if (!rec || !Array.isArray(rec.sessionIds)) continue;
248
+ if (!rec || !Array.isArray(rec.sessionIds)) continue
207
249
  if (!rec.sessionIds.includes(sessionId)) {
208
- await workspaces.put(wid, { ...rec, sessionIds: rec.sessionIds.concat([sessionId]) });
250
+ await workspaces.put(wid, { ...rec, sessionIds: rec.sessionIds.concat([sessionId]) })
209
251
  }
210
252
  }
211
- } catch { /* unit absent */ }
253
+ } catch {
254
+ /* unit absent */
255
+ }
212
256
  }
213
257
  if (ws && ws.global) {
214
258
  try {
215
- const state = ws.global.get();
259
+ const state = ws.global.get()
216
260
  if (state) {
217
- const next = { ...state };
261
+ const next = { ...state }
218
262
  if (meta.archived && Array.isArray(next.archivedSessionIds) && !next.archivedSessionIds.includes(sessionId)) {
219
- next.archivedSessionIds = next.archivedSessionIds.concat([sessionId]);
263
+ next.archivedSessionIds = next.archivedSessionIds.concat([sessionId])
220
264
  }
221
265
  if (meta.pinned && Array.isArray(next.pinnedSessionIds) && !next.pinnedSessionIds.includes(sessionId)) {
222
- next.pinnedSessionIds = next.pinnedSessionIds.concat([sessionId]);
266
+ next.pinnedSessionIds = next.pinnedSessionIds.concat([sessionId])
223
267
  }
224
- await ws.global.set(next);
268
+ await ws.global.set(next)
225
269
  }
226
- } catch { /* no global slot */ }
270
+ } catch {
271
+ /* no global slot */
272
+ }
227
273
  }
228
274
  }
229
275
 
230
276
  function moveDir(src, dst) {
231
- fs.mkdirSync(path.dirname(dst), { recursive: true });
277
+ fs.mkdirSync(path.dirname(dst), { recursive: true })
232
278
  try {
233
- fs.renameSync(src, dst);
279
+ fs.renameSync(src, dst)
234
280
  } catch (err) {
235
- if (!err || err.code !== "EXDEV") throw err;
236
- fs.cpSync(src, dst, { recursive: true, errorOnExist: true });
237
- fs.rmSync(src, { recursive: true, force: true });
281
+ if (!err || err.code !== 'EXDEV') throw err
282
+ fs.cpSync(src, dst, { recursive: true, errorOnExist: true })
283
+ fs.rmSync(src, { recursive: true, force: true })
238
284
  }
239
285
  }
240
286
 
241
287
  function writeManifest(dir, manifest) {
242
- fs.mkdirSync(dir, { recursive: true });
243
- const tmp = path.join(dir, "manifest.json.tmp");
244
- fs.writeFileSync(tmp, JSON.stringify(manifest, null, 2));
245
- fs.renameSync(tmp, path.join(dir, "manifest.json"));
288
+ fs.mkdirSync(dir, { recursive: true })
289
+ const tmp = path.join(dir, 'manifest.json.tmp')
290
+ fs.writeFileSync(tmp, JSON.stringify(manifest, null, 2))
291
+ fs.renameSync(tmp, path.join(dir, 'manifest.json'))
246
292
  }
247
293
 
248
294
  function assertTrashId(trashId) {
249
- if (typeof trashId !== "string" || !TRASH_ID_RE.test(trashId)) throw new OpsError("invalid trashId", 400);
295
+ if (typeof trashId !== 'string' || !TRASH_ID_RE.test(trashId)) throw new OpsError('invalid trashId', 400)
250
296
  }
251
297
 
252
298
  function readManifest(trashId) {
253
- assertTrashId(trashId);
254
- const file = path.join(trashRoot(), trashId, "manifest.json");
255
- let raw;
256
- try { raw = fs.readFileSync(file, "utf8"); } catch { throw new OpsError("trash entry not found", 404); }
257
- try { return JSON.parse(raw); } catch { throw new OpsError("corrupt trash manifest", 500); }
299
+ assertTrashId(trashId)
300
+ const file = path.join(trashRoot(), trashId, 'manifest.json')
301
+ let raw
302
+ try {
303
+ raw = fs.readFileSync(file, 'utf8')
304
+ } catch {
305
+ throw new OpsError('trash entry not found', 404)
306
+ }
307
+ try {
308
+ return JSON.parse(raw)
309
+ } catch {
310
+ throw new OpsError('corrupt trash manifest', 500)
311
+ }
258
312
  }
259
313
 
260
314
  function agentRunning(ctx, sessionId) {
261
- let agents;
262
- try { agents = ctx && typeof ctx.get === "function" ? ctx.get("agents") : undefined; } catch { return false; }
263
- if (!agents || typeof agents.get !== "function") return false;
315
+ let agents
316
+ try {
317
+ agents = ctx && typeof ctx.get === 'function' ? ctx.get('agents') : undefined
318
+ } catch {
319
+ return false
320
+ }
321
+ if (!agents || typeof agents.get !== 'function') return false
264
322
  for (const variant of sessionIdVariants(sessionId)) {
265
- const agent = agents.get(variant);
266
- if (agent && agent.status === "running") return true;
323
+ const agent = agents.get(variant)
324
+ if (agent && agent.status === 'running') return true
267
325
  }
268
- return false;
326
+ return false
269
327
  }
270
328
 
271
329
  /**
@@ -273,62 +331,68 @@ function agentRunning(ctx, sessionId) {
273
331
  * confirmation titles; the caller must pass the title shown in the UI.
274
332
  */
275
333
  export async function deleteSessionToTrash(ctx, sessionId, confirmTitle) {
276
- if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
277
- const dirs = findAllSessionDirs(sessionId);
278
- if (dirs.length === 0) throw new OpsError("session not found", 404);
279
- if (dirs.length > 1) throw new OpsError(`ambiguous session id: found ${dirs.length} directories`, 409);
280
- if (agentRunning(ctx, sessionId)) throw new OpsError("session is running; stop it first", 409);
281
-
282
- const meta = readMetadata(ctx, sessionId);
283
- const title = titleOfRow(meta.projRow) || headerTitle(dirs[0].dir);
284
- const expected = title || sessionId;
285
- if (String(confirmTitle == null ? "" : confirmTitle).trim() !== expected) {
286
- throw new OpsError(`title mismatch: type "${expected}" to delete`, 400);
287
- }
288
-
289
- const now = Date.now();
290
- const trashId = `${now}-${randomUUID().slice(0, 8)}`;
291
- const root = path.join(trashRoot(), trashId);
292
- const rel = path.relative(sessionsRoot(), dirs[0].dir);
293
- const dataRel = path.join("data", rel);
334
+ if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
335
+ const dirs = findAllSessionDirs(sessionId)
336
+ if (dirs.length === 0) throw new OpsError('session not found', 404)
337
+ if (dirs.length > 1) throw new OpsError(`ambiguous session id: found ${dirs.length} directories`, 409)
338
+ if (agentRunning(ctx, sessionId)) throw new OpsError('session is running; stop it first', 409)
339
+
340
+ const meta = readMetadata(ctx, sessionId)
341
+ const title = titleOfRow(meta.projRow) || headerTitle(dirs[0].dir)
342
+ const expected = title || sessionId
343
+ if (String(confirmTitle == null ? '' : confirmTitle).trim() !== expected) {
344
+ throw new OpsError(`title mismatch: type "${expected}" to delete`, 400)
345
+ }
346
+
347
+ const now = Date.now()
348
+ const trashId = `${now}-${randomUUID().slice(0, 8)}`
349
+ const root = path.join(trashRoot(), trashId)
350
+ const rel = path.relative(sessionsRoot(), dirs[0].dir)
351
+ const dataRel = path.join('data', rel)
294
352
  const manifest = {
295
353
  version: 1,
296
354
  trashId,
297
355
  sessionId,
298
356
  title: title || null,
299
- state: "moving",
357
+ state: 'moving',
300
358
  deletedAt: now,
301
359
  expiresAt: now + TRASH_RETENTION_MS,
302
360
  dirs: [{ rel, originalSlug: dirs[0].slug, originalName: dirs[0].name }],
303
361
  ...meta,
304
- };
305
- writeManifest(root, manifest);
362
+ }
363
+ writeManifest(root, manifest)
306
364
 
307
- const source = dirs[0].dir;
308
- const target = path.join(root, dataRel);
309
- let moved = false;
365
+ const source = dirs[0].dir
366
+ const target = path.join(root, dataRel)
367
+ let moved = false
310
368
  try {
311
- moveDir(source, target);
312
- moved = true;
313
- if (findAllSessionDirs(sessionId).length > 0) throw new OpsError("session directory still present after move", 500);
314
- await stripMetadata(ctx, sessionId, meta);
315
- manifest.state = "trashed";
316
- writeManifest(root, manifest);
369
+ moveDir(source, target)
370
+ moved = true
371
+ if (findAllSessionDirs(sessionId).length > 0) throw new OpsError('session directory still present after move', 500)
372
+ await stripMetadata(ctx, sessionId, meta)
373
+ manifest.state = 'trashed'
374
+ writeManifest(root, manifest)
317
375
  } catch (err) {
318
- let dataBack = !moved && fs.existsSync(source) && !fs.existsSync(target);
319
- let metadataBack = dataBack;
376
+ let dataBack = !moved && fs.existsSync(source) && !fs.existsSync(target)
377
+ let metadataBack = dataBack
320
378
  if (moved) {
321
379
  try {
322
- moveDir(target, source);
323
- dataBack = true;
324
- await restoreMetadata(ctx, sessionId, meta);
325
- metadataBack = true;
326
- } catch { /* leave the manifest for manual restore */ }
380
+ moveDir(target, source)
381
+ dataBack = true
382
+ await restoreMetadata(ctx, sessionId, meta)
383
+ metadataBack = true
384
+ } catch {
385
+ /* leave the manifest for manual restore */
386
+ }
327
387
  }
328
388
  if (dataBack && metadataBack) {
329
- try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* best effort */ }
389
+ try {
390
+ fs.rmSync(root, { recursive: true, force: true })
391
+ } catch {
392
+ /* best effort */
393
+ }
330
394
  }
331
- throw err;
395
+ throw err
332
396
  }
333
397
 
334
398
  return {
@@ -340,93 +404,115 @@ export async function deleteSessionToTrash(ctx, sessionId, confirmTitle) {
340
404
  workspaceIds: meta.workspaceIds,
341
405
  archived: meta.archived,
342
406
  pinned: meta.pinned,
343
- };
407
+ }
344
408
  }
345
409
 
346
410
  export async function listTrash(ctx, { purgeExpired = false, now = Date.now() } = {}) {
347
- let names = [];
348
- try { names = fs.readdirSync(trashRoot(), { withFileTypes: true }); } catch { return []; }
349
- const entries = [];
411
+ let names = []
412
+ try {
413
+ names = fs.readdirSync(trashRoot(), { withFileTypes: true })
414
+ } catch {
415
+ return []
416
+ }
417
+ const entries = []
350
418
  for (const name of names) {
351
- if (!name.isDirectory() || !TRASH_ID_RE.test(name.name)) continue;
352
- let manifest;
353
- try { manifest = readManifest(name.name); } catch { continue; }
354
- if (purgeExpired && typeof manifest.expiresAt === "number" && manifest.expiresAt <= now) {
355
- try { fs.rmSync(path.join(trashRoot(), name.name), { recursive: true, force: true }); } catch { /* retry next time */ }
356
- continue;
419
+ if (!name.isDirectory() || !TRASH_ID_RE.test(name.name)) continue
420
+ let manifest
421
+ try {
422
+ manifest = readManifest(name.name)
423
+ } catch {
424
+ continue
425
+ }
426
+ if (purgeExpired && typeof manifest.expiresAt === 'number' && manifest.expiresAt <= now) {
427
+ try {
428
+ fs.rmSync(path.join(trashRoot(), name.name), { recursive: true, force: true })
429
+ } catch {
430
+ /* retry next time */
431
+ }
432
+ continue
357
433
  }
358
434
  entries.push({
359
435
  trashId: name.name,
360
436
  sessionId: manifest.sessionId,
361
437
  title: manifest.title || null,
362
- state: manifest.state || "trashed",
438
+ state: manifest.state || 'trashed',
363
439
  deletedAt: manifest.deletedAt || null,
364
440
  expiresAt: manifest.expiresAt || null,
365
441
  workspaceIds: Array.isArray(manifest.workspaceIds) ? manifest.workspaceIds : [],
366
- });
442
+ })
367
443
  }
368
- entries.sort((a, b) => (b.deletedAt || 0) - (a.deletedAt || 0));
369
- return entries;
444
+ entries.sort((a, b) => (b.deletedAt || 0) - (a.deletedAt || 0))
445
+ return entries
370
446
  }
371
447
 
372
448
  function restoreTarget(manifest) {
373
449
  if (!manifest || !Array.isArray(manifest.dirs) || manifest.dirs.length !== 1) {
374
- throw new OpsError("unsupported trash manifest", 500);
450
+ throw new OpsError('unsupported trash manifest', 500)
375
451
  }
376
452
  if (!isSessionId(manifest.sessionId)) {
377
- throw new OpsError("invalid trash manifest sessionId", 500);
453
+ throw new OpsError('invalid trash manifest sessionId', 500)
378
454
  }
379
- const raw = manifest.dirs[0].rel;
380
- if (typeof raw !== "string" || raw.length === 0 || path.isAbsolute(raw)) {
381
- throw new OpsError("invalid trash manifest rel", 500);
455
+ const raw = manifest.dirs[0].rel
456
+ if (typeof raw !== 'string' || raw.length === 0 || path.isAbsolute(raw)) {
457
+ throw new OpsError('invalid trash manifest rel', 500)
382
458
  }
383
- const parts = raw.split(/[\\/]+/);
384
- if (parts.length !== 2 || parts.some((part) => !part || part === "." || part === "..")) {
385
- throw new OpsError("invalid trash manifest rel", 500);
459
+ const parts = raw.split(/[\\/]+/)
460
+ if (parts.length !== 2 || parts.some(part => !part || part === '.' || part === '..')) {
461
+ throw new OpsError('invalid trash manifest rel', 500)
386
462
  }
387
463
  if (!sessionIdVariants(manifest.sessionId).includes(parts[1])) {
388
- throw new OpsError("trash manifest rel does not match sessionId", 500);
464
+ throw new OpsError('trash manifest rel does not match sessionId', 500)
389
465
  }
390
- const root = path.resolve(sessionsRoot());
391
- const target = path.join(root, ...parts);
466
+ const root = path.resolve(sessionsRoot())
467
+ const target = path.join(root, ...parts)
392
468
  if (!target.startsWith(root + path.sep)) {
393
- throw new OpsError("trash manifest rel escapes the sessions root", 500);
469
+ throw new OpsError('trash manifest rel escapes the sessions root', 500)
394
470
  }
395
- return { rel: path.join(...parts), target };
471
+ return { rel: path.join(...parts), target }
396
472
  }
397
473
 
398
474
  export async function restoreTrash(ctx, trashId) {
399
- const manifest = readManifest(trashId);
400
- const { rel, target } = restoreTarget(manifest);
401
- if (fs.existsSync(target)) throw new OpsError("session directory already exists; refusing to overwrite", 409);
475
+ const manifest = readManifest(trashId)
476
+ const { rel, target } = restoreTarget(manifest)
477
+ if (fs.existsSync(target)) throw new OpsError('session directory already exists; refusing to overwrite', 409)
402
478
 
403
- const root = path.join(trashRoot(), trashId);
404
- const source = path.join(root, "data", rel);
405
- let sourceStat;
406
- try { sourceStat = fs.lstatSync(source); } catch { throw new OpsError("trash payload missing", 404); }
407
- if (!sourceStat.isDirectory()) throw new OpsError("trash payload is not a directory", 500);
479
+ const root = path.join(trashRoot(), trashId)
480
+ const source = path.join(root, 'data', rel)
481
+ let sourceStat
482
+ try {
483
+ sourceStat = fs.lstatSync(source)
484
+ } catch {
485
+ throw new OpsError('trash payload missing', 404)
486
+ }
487
+ if (!sourceStat.isDirectory()) throw new OpsError('trash payload is not a directory', 500)
408
488
 
409
489
  try {
410
- moveDir(source, target);
411
- if (!fs.existsSync(target)) throw new OpsError("restore move failed", 500);
412
- await restoreMetadata(ctx, manifest.sessionId, manifest);
490
+ moveDir(source, target)
491
+ if (!fs.existsSync(target)) throw new OpsError('restore move failed', 500)
492
+ await restoreMetadata(ctx, manifest.sessionId, manifest)
413
493
  } catch (err) {
414
494
  try {
415
- if (fs.existsSync(target) && !fs.existsSync(source)) moveDir(target, source);
416
- } catch { /* leave both for manual recovery */ }
417
- throw err;
495
+ if (fs.existsSync(target) && !fs.existsSync(source)) moveDir(target, source)
496
+ } catch {
497
+ /* leave both for manual recovery */
498
+ }
499
+ throw err
418
500
  }
419
501
 
420
- try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* manifest cleanup is best effort */ }
421
- return { ok: true, trashId, sessionId: manifest.sessionId, title: manifest.title || null };
502
+ try {
503
+ fs.rmSync(root, { recursive: true, force: true })
504
+ } catch {
505
+ /* manifest cleanup is best effort */
506
+ }
507
+ return { ok: true, trashId, sessionId: manifest.sessionId, title: manifest.title || null }
422
508
  }
423
509
 
424
510
  export async function purgeTrash(ctx, trashId) {
425
- assertTrashId(trashId);
426
- const root = path.join(trashRoot(), trashId);
427
- if (!fs.existsSync(root)) throw new OpsError("trash entry not found", 404);
428
- fs.rmSync(root, { recursive: true, force: true });
429
- return { ok: true, trashId };
511
+ assertTrashId(trashId)
512
+ const root = path.join(trashRoot(), trashId)
513
+ if (!fs.existsSync(root)) throw new OpsError('trash entry not found', 404)
514
+ fs.rmSync(root, { recursive: true, force: true })
515
+ return { ok: true, trashId }
430
516
  }
431
517
 
432
- export const _internals = { findAllSessionDirs, readMetadata, stripMetadata, restoreMetadata };
518
+ export const _internals = { findAllSessionDirs, readMetadata, stripMetadata, restoreMetadata }