@michengai/dsh-archive-manager 1.4.2 → 1.5.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.
@@ -1,15 +1,32 @@
1
1
  import { bindArchiveManagerRemote, installArchiveWorkspace } from "./workspace.js";
2
+ import { installSessionLifecycle } from "./session-lifecycle.js";
2
3
  const inject = ["workspaceRegistry", "sessionPersistence", "typert"];
3
4
  async function apply(ctx) {
4
5
  const registry = ctx.workspaceRegistry;
5
6
  const uninstallWorkspace = installArchiveWorkspace(registry);
6
7
  let unbindRemote = () => {
7
8
  };
9
+ let uninstallLifecycle = () => {
10
+ };
11
+ if (typeof ctx.inject === "function") {
12
+ ctx.inject(["agents"], (agentCtx) => {
13
+ uninstallLifecycle = installSessionLifecycle(agentCtx);
14
+ return () => {
15
+ uninstallLifecycle();
16
+ };
17
+ });
18
+ } else if (ctx.get?.("agents") || ctx.agents) {
19
+ uninstallLifecycle = installSessionLifecycle(ctx);
20
+ }
8
21
  const dispose = async () => {
9
22
  try {
10
23
  unbindRemote();
11
24
  } finally {
12
- uninstallWorkspace();
25
+ try {
26
+ uninstallLifecycle();
27
+ } finally {
28
+ uninstallWorkspace();
29
+ }
13
30
  }
14
31
  };
15
32
  try {
@@ -0,0 +1,163 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { symbols } from "@deepseek-ai/cordis";
3
+ const runtimes = /* @__PURE__ */ new WeakMap();
4
+ const migrationContext = new AsyncLocalStorage();
5
+ function getRaw(value) {
6
+ if (value && typeof value === "object") {
7
+ const original = Reflect.get(value, symbols.original);
8
+ if (original !== null && typeof original === "object") return original;
9
+ }
10
+ return value;
11
+ }
12
+ function migrationInProgressError() {
13
+ const err = new Error("\u8BE5\u4F1A\u8BDD\u6B63\u5728\u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002");
14
+ err.code = "migration-in-progress";
15
+ return err;
16
+ }
17
+ function installSessionLifecycle(owner) {
18
+ const agentsObj = typeof owner.get === "function" ? owner.get("agents") : owner.agents;
19
+ const rawAgents = getRaw(agentsObj);
20
+ if (!rawAgents || typeof rawAgents !== "object") return () => {
21
+ };
22
+ if (runtimes.has(rawAgents)) return () => {
23
+ };
24
+ const runtime = { handles: /* @__PURE__ */ new Map(), moving: /* @__PURE__ */ new Set() };
25
+ runtimes.set(rawAgents, runtime);
26
+ const restore = [];
27
+ for (const method of ["create", "resume"]) {
28
+ const originalMethod = rawAgents[method];
29
+ if (typeof originalMethod !== "function") continue;
30
+ const wrapped = async function(options, ...args) {
31
+ const id = options?.sessionId ?? options?.resumeSessionId;
32
+ if (id && runtime.moving.has(id) && migrationContext.getStore() !== runtime) {
33
+ throw migrationInProgressError();
34
+ }
35
+ const handle = await Reflect.apply(originalMethod, this, [options, ...args]);
36
+ const agent = getRaw(handle?.agent);
37
+ if (agent?.id && typeof handle?.dispose === "function") {
38
+ const guards = [];
39
+ runtime.handles.set(agent.id, { handle, agent, guards });
40
+ for (const actionName of ["send", "followup", "runMaintenance", "steer", "inject"]) {
41
+ const action = agent[actionName];
42
+ if (typeof action !== "function") continue;
43
+ const guarded = function(...params) {
44
+ if (runtime.moving.has(agent.id) && migrationContext.getStore() !== runtime || getRaw(rawAgents.get?.(agent.id)) !== agent) {
45
+ throw migrationInProgressError();
46
+ }
47
+ return Reflect.apply(action, this, params);
48
+ };
49
+ agent[actionName] = guarded;
50
+ guards.push(() => {
51
+ if (agent[actionName] === guarded) agent[actionName] = action;
52
+ });
53
+ }
54
+ }
55
+ return handle;
56
+ };
57
+ rawAgents[method] = wrapped;
58
+ restore.push(() => {
59
+ if (rawAgents[method] === wrapped) rawAgents[method] = originalMethod;
60
+ });
61
+ }
62
+ owner.on?.("agent/disposed", (payload) => {
63
+ const agent = getRaw(payload?.agent);
64
+ if (agent?.id) {
65
+ const entry = runtime.handles.get(agent.id);
66
+ if (entry && getRaw(entry.agent) === agent) {
67
+ runtime.handles.delete(agent.id);
68
+ }
69
+ }
70
+ });
71
+ return () => {
72
+ for (const entry of runtime.handles.values()) {
73
+ for (const undo of entry.guards) undo();
74
+ }
75
+ runtime.handles.clear();
76
+ for (const undo of restore.reverse()) undo();
77
+ runtimes.delete(rawAgents);
78
+ };
79
+ }
80
+ function lifecycleFor(ctx, sessionId) {
81
+ const agentsObj = typeof ctx.get === "function" ? ctx.get("agents") : ctx.agents;
82
+ const rawAgents = getRaw(agentsObj);
83
+ if (!rawAgents || typeof rawAgents !== "object") return null;
84
+ const runtime = runtimes.get(rawAgents);
85
+ if (!runtime) return null;
86
+ const entry = runtime.handles.get(sessionId);
87
+ if (!entry) return null;
88
+ const currentAgent = rawAgents.get ? rawAgents.get(sessionId) : void 0;
89
+ if (!currentAgent || getRaw(currentAgent) !== getRaw(entry.agent)) return null;
90
+ return { ...entry, runtime, agents: rawAgents };
91
+ }
92
+ async function withReleasedSession(ctx, sessionId, operation, options) {
93
+ const owned = lifecycleFor(ctx, sessionId);
94
+ if (!owned) {
95
+ return operation();
96
+ }
97
+ const controller = ctx.sessionController ?? (typeof ctx.get === "function" ? ctx.get("sessionController") : void 0);
98
+ if (typeof controller?.resolveAgent !== "function") {
99
+ return operation();
100
+ }
101
+ const { handle, agent, runtime } = owned;
102
+ const executing = agent.busy === true || agent.status === "running" || agent.session?.running === true || agent.session?.status === "running" || agent.session?.status === "ongoing";
103
+ if (executing) {
104
+ throw new Error("\u8BE5\u4F1A\u8BDD\u6B63\u5904\u4E8E\u6267\u884C\u6216\u8FD0\u884C\u72B6\u6001\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210\u540E\u518D\u79FB\u52A8\u3002");
105
+ }
106
+ const header = agent.session?.header;
107
+ if (header?.origin === "subagent" || (Number(header?.delegationDepth) || 0) > 0) {
108
+ throw new Error("\u5B50\u4EE3\u7406\uFF08subagent\uFF09\u4F1A\u8BDD\u4E0D\u652F\u6301\u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u3002");
109
+ }
110
+ if (header?.origin === "side") {
111
+ throw new Error("\u65C1\u8DEF\uFF08side\uFF09\u4F1A\u8BDD\u4E0D\u652F\u6301\u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u3002");
112
+ }
113
+ runtime.moving.add(sessionId);
114
+ let failure = void 0;
115
+ let result;
116
+ try {
117
+ await handle.dispose();
118
+ result = await operation();
119
+ } catch (error) {
120
+ failure = error;
121
+ throw error;
122
+ } finally {
123
+ runtime.handles.delete(sessionId);
124
+ try {
125
+ if (typeof controller?.resolveAgent === "function") {
126
+ const restored = await migrationContext.run(
127
+ runtime,
128
+ () => controller.resolveAgent(sessionId)
129
+ );
130
+ if (restored?.error) {
131
+ throw restored.error;
132
+ }
133
+ runtime.moving.delete(sessionId);
134
+ if (!failure && options?.targetPath && restored?.agent) {
135
+ const workingDirectory = ctx.workingDirectory ?? (typeof ctx.get === "function" ? ctx.get("workingDirectory") : void 0);
136
+ if (typeof workingDirectory?.set === "function") {
137
+ await migrationContext.run(
138
+ runtime,
139
+ () => workingDirectory.set(restored.agent, options.targetPath)
140
+ );
141
+ }
142
+ }
143
+ }
144
+ } catch (error) {
145
+ if (!failure) {
146
+ ctx.logger?.warn?.(
147
+ `[archive-manager] \u4F1A\u8BDD ${sessionId} \u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u5DF2\u843D\u76D8\uFF0C\u4F46\u5728\u76EE\u6807\u5DE5\u4F5C\u533A\u91CD\u65B0\u6302\u63A5\u6216\u540C\u6B65\u76EE\u5F55\u5F02\u5E38: ${error instanceof Error ? error.message : String(error)}`
148
+ );
149
+ }
150
+ } finally {
151
+ runtime.moving.delete(sessionId);
152
+ }
153
+ }
154
+ if (failure) throw failure;
155
+ return result;
156
+ }
157
+ export {
158
+ installSessionLifecycle,
159
+ lifecycleFor,
160
+ migrationContext,
161
+ migrationInProgressError,
162
+ withReleasedSession
163
+ };
@@ -1,6 +1,7 @@
1
1
  import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
2
  import { dirname, join, normalize, resolve } from "node:path";
3
3
  import zlib from "node:zlib";
4
+ import { withReleasedSession } from "./session-lifecycle.js";
4
5
  const ZSTD_MAGIC = 4247762216;
5
6
  const CHECKSUM_OPTS = { params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 } };
6
7
  function normalizePath(p) {
@@ -133,6 +134,9 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
133
134
  if (header.origin === "subagent") {
134
135
  throw new Error("\u5B50\u4EE3\u7406\uFF08subagent\uFF09\u4F1A\u8BDD\u4E0D\u652F\u6301\u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u3002");
135
136
  }
137
+ if (header.origin === "side") {
138
+ throw new Error("\u65C1\u8DEF\uFF08side\uFF09\u4F1A\u8BDD\u4E0D\u652F\u6301\u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u3002");
139
+ }
136
140
  const currentNormalizedCwd = normalizePath(header.cwd);
137
141
  const targetNormalizedCwd = normalizePath(targetPath);
138
142
  const targetNorm = normalizePath(targetWorkspace.path);
@@ -142,23 +146,23 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
142
146
  return isOther && rawWorkspaceSessionIds(ws).includes(cleanSessionId);
143
147
  });
144
148
  if (currentNormalizedCwd && targetNormalizedCwd && currentNormalizedCwd === targetNormalizedCwd) {
145
- const targetHadSession2 = rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId);
146
- const previousPath2 = registry.sessionPaths?.get(cleanSessionId);
147
- const previousInvalidPath2 = getInvalidSessionState(registry.invalidSessionPaths, cleanSessionId);
148
- const wasMissing2 = registry.missingSessionPaths?.has(cleanSessionId);
149
- const attemptedSources2 = [];
149
+ const targetHadSession = rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId);
150
+ const previousPath = registry.sessionPaths?.get(cleanSessionId);
151
+ const previousInvalidPath = getInvalidSessionState(registry.invalidSessionPaths, cleanSessionId);
152
+ const wasMissing = registry.missingSessionPaths?.has(cleanSessionId);
153
+ const attemptedSources = [];
150
154
  try {
151
155
  await targetWorkspace.attachSession(cleanSessionId);
152
156
  if (!rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
153
157
  throw new Error("\u76EE\u6807\u5DE5\u4F5C\u533A\u672A\u4FDD\u7559\u4F1A\u8BDD\u5173\u8054\uFF0C\u5DF2\u53D6\u6D88\u79FB\u52A8\u3002");
154
158
  }
155
159
  for (const ws of sourceWorkspaces) {
156
- attemptedSources2.push(ws);
160
+ attemptedSources.push(ws);
157
161
  await ws.detachSession(cleanSessionId);
158
162
  }
159
163
  } catch (error) {
160
164
  const rollbackErrors = [];
161
- for (const ws of attemptedSources2) {
165
+ for (const ws of attemptedSources) {
162
166
  if (rawWorkspaceSessionIds(ws).includes(cleanSessionId)) continue;
163
167
  try {
164
168
  await ws.attachSession(cleanSessionId);
@@ -169,7 +173,7 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
169
173
  rollbackErrors.push(restoreError);
170
174
  }
171
175
  }
172
- if (!rollbackErrors.length && !targetHadSession2 && rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
176
+ if (!rollbackErrors.length && !targetHadSession && rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
173
177
  try {
174
178
  await targetWorkspace.detachSession(cleanSessionId);
175
179
  } catch (restoreError) {
@@ -179,10 +183,10 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
179
183
  if (rollbackErrors.length) {
180
184
  throw new AggregateError([error, ...rollbackErrors], `\u79FB\u52A8\u5931\u8D25\uFF0C\u4E14\u672A\u80FD\u5B8C\u6574\u6062\u590D\u5DE5\u4F5C\u533A\u5173\u8054\uFF1A${String(error)}`);
181
185
  }
182
- if (previousPath2 === void 0) registry.sessionPaths?.delete(cleanSessionId);
183
- else registry.sessionPaths?.set(cleanSessionId, previousPath2);
184
- restoreInvalidSessionState(registry.invalidSessionPaths, cleanSessionId, previousInvalidPath2);
185
- if (!wasMissing2) registry.missingSessionPaths?.delete(cleanSessionId);
186
+ if (previousPath === void 0) registry.sessionPaths?.delete(cleanSessionId);
187
+ else registry.sessionPaths?.set(cleanSessionId, previousPath);
188
+ restoreInvalidSessionState(registry.invalidSessionPaths, cleanSessionId, previousInvalidPath);
189
+ if (!wasMissing) registry.missingSessionPaths?.delete(cleanSessionId);
186
190
  else registry.missingSessionPaths?.add(cleanSessionId);
187
191
  throw error;
188
192
  }
@@ -220,159 +224,166 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
220
224
  toWorkspacePath: targetPath
221
225
  };
222
226
  }
223
- const requireReleasedSession = () => {
224
- if (ctx.sessions?.get?.(cleanSessionId) || ctx.agents?.get?.(cleanSessionId)) {
225
- throw new Error("\u8BE5\u4F1A\u8BDD\u4ECD\u88AB\u5BBF\u4E3B\u6301\u6709\uFF0C\u65E0\u6CD5\u8DE8\u76EE\u5F55\u79FB\u52A8\u3002\u8BF7\u5148\u5173\u95ED\u8BE5\u4F1A\u8BDD\u518D\u91CD\u8BD5\u3002");
226
- }
227
- };
228
- requireReleasedSession();
229
- if (!persistence || typeof persistence.locate !== "function") {
230
- throw new Error("\u5F53\u524D\u6301\u4E45\u5316\u540E\u7AEF\u4E0D\u652F\u6301\u7269\u7406\u5B9A\u4F4D\uFF0C\u65E0\u6CD5\u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u4F1A\u8BDD\u3002");
231
- }
232
- const sourceLoc = persistence.locate({ id: cleanSessionId, cwd: header.cwd });
233
- const targetLoc = persistence.locate({ id: cleanSessionId, cwd: targetPath });
234
- if (!sourceLoc || !targetLoc || !sourceLoc.path || !targetLoc.path) {
235
- throw new Error("\u6301\u4E45\u5316\u540E\u7AEF\u65E0\u6CD5\u5B9A\u4F4D\u4F1A\u8BDD\u5DE5\u4EF6\u8DEF\u5F84\u3002");
236
- }
237
- const sourceLogPath = sourceLoc.path;
238
- const targetLogPath = targetLoc.path;
239
- const sourceSessionDir = dirname(sourceLogPath);
240
- const targetSessionDir = dirname(targetLogPath);
241
- let targetOccupied = false;
242
- try {
243
- await stat(targetLogPath);
244
- targetOccupied = true;
245
- } catch {
246
- }
247
- if (targetOccupied) {
248
- throw new Error(`\u76EE\u6807\u5DE5\u4F5C\u533A\u5DF2\u5B58\u5728\u540C\u540D\u4F1A\u8BDD\u5DE5\u4EF6\uFF0C\u62D2\u7EDD\u8986\u76D6: ${targetLogPath}`);
249
- }
250
- const persistenceRoot = persistence.root ?? persistence.config?.root;
251
- const backupRoot = persistenceRoot ? join(dirname(resolve(persistenceRoot)), "dsham-move-backup") : join(dirname(sourceSessionDir), ".dsham-move-backup");
252
- await mkdir(backupRoot, { recursive: true });
253
- const safeSessionName = encodeURIComponent(cleanSessionId).replace(/%/g, "~");
254
- const backupDir = join(backupRoot, `${safeSessionName}-${process.pid}-${Date.now()}`);
255
- const isZstd = sourceLogPath.endsWith(".zstd");
256
- const sourceBytes = await readFile(sourceLogPath);
257
- const newBytes = rewriteSessionArtifactCwd(sourceBytes, targetPath, isZstd);
258
- if (isZstd) {
259
- const f0 = zlib.zstdDecompressSync(newBytes);
260
- const f0Obj = JSON.parse(f0.toString("utf8").split("\n")[0]);
261
- if (f0Obj.id !== cleanSessionId || f0Obj.cwd !== targetPath) {
262
- throw new Error("\u8FC1\u79FB\u524D\u6821\u9A8C\u5931\u8D25\uFF1A\u6570\u636E\u6539\u5199\u9A8C\u8BC1\u672A\u901A\u8FC7\u3002");
263
- }
264
- }
265
- requireReleasedSession();
266
- const targetHadSession = rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId);
267
- const previousPath = registry.sessionPaths?.get(cleanSessionId);
268
- const previousInvalidPath = getInvalidSessionState(registry.invalidSessionPaths, cleanSessionId);
269
- const wasMissing = registry.missingSessionPaths?.has(cleanSessionId) ?? false;
270
- const attemptedSources = [];
271
- let targetAttached = false;
272
- let stageFile = null;
273
- let sourceDirMoved = false;
274
- try {
275
- await rename(sourceSessionDir, backupDir);
276
- sourceDirMoved = true;
277
- await mkdir(targetSessionDir, { recursive: true });
278
- stageFile = join(targetSessionDir, `.stage-${process.pid}-${Date.now()}`);
279
- await writeFile(stageFile, newBytes);
280
- await rename(stageFile, targetLogPath);
281
- stageFile = null;
282
- const readbackBytes = await readFile(targetLogPath);
283
- if (readbackBytes.length === 0) throw new Error("\u76EE\u6807\u5199\u5165\u5DE5\u4EF6\u4E3A\u7A7A");
284
- const targetHeader = { ...header, cwd: targetPath };
285
- registry.sessionPaths?.set(cleanSessionId, targetPath);
286
- registry.headers?.set(cleanSessionId, targetHeader);
287
- registry.invalidSessionPaths?.delete(cleanSessionId);
288
- await targetWorkspace.attachSession(cleanSessionId);
289
- if (!rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
290
- throw new Error("\u76EE\u6807\u5DE5\u4F5C\u533A\u672A\u4FDD\u7559\u4F1A\u8BDD\u5173\u8054\uFF0C\u5DF2\u53D6\u6D88\u79FB\u52A8\u3002");
291
- }
292
- targetAttached = true;
293
- for (const ws of sourceWorkspaces) {
294
- attemptedSources.push(ws);
295
- await ws.detachSession(cleanSessionId);
296
- }
297
- if (ctx.sessionProjectionCache && typeof ctx.sessionProjectionCache.coldSnapshot === "function") {
298
- try {
299
- if (ctx.sessionProjectionCache.coldSnapshot.length === 1) {
300
- await ctx.sessionProjectionCache.coldSnapshot(cleanSessionId);
301
- } else if (persistence && typeof persistence.open === "function") {
302
- const readHandle = await persistence.open(cleanSessionId, "read");
303
- try {
304
- const { events } = typeof readHandle.read === "function" ? await readHandle.read(0) : { events: [] };
305
- const coldMeta = readHandle.header ?? targetHeader;
306
- const inherited = readHandle.inheritedEventCount ?? 0;
307
- await ctx.sessionProjectionCache.coldSnapshot(
308
- coldMeta,
309
- inherited,
310
- events ?? []
311
- );
312
- } finally {
313
- await readHandle.close();
314
- }
227
+ return withReleasedSession(
228
+ ctx,
229
+ cleanSessionId,
230
+ async () => {
231
+ const requireReleasedSession = () => {
232
+ if (ctx.sessions?.get?.(cleanSessionId) || ctx.agents?.get?.(cleanSessionId)) {
233
+ throw new Error("\u8BE5\u4F1A\u8BDD\u4ECD\u88AB\u5BBF\u4E3B\u6301\u6709\uFF0C\u65E0\u6CD5\u8DE8\u76EE\u5F55\u79FB\u52A8\u3002\u8BF7\u5148\u5173\u95ED\u8BE5\u4F1A\u8BDD\u518D\u91CD\u8BD5\u3002");
315
234
  }
316
- } catch (err) {
317
- ctx.logger?.warn?.(`archive-manager: post-move coldSnapshot failed: ${String(err)}`);
235
+ };
236
+ requireReleasedSession();
237
+ if (!persistence || typeof persistence.locate !== "function") {
238
+ throw new Error("\u5F53\u524D\u6301\u4E45\u5316\u540E\u7AEF\u4E0D\u652F\u6301\u7269\u7406\u5B9A\u4F4D\uFF0C\u65E0\u6CD5\u8DE8\u5DE5\u4F5C\u533A\u79FB\u52A8\u4F1A\u8BDD\u3002");
318
239
  }
319
- }
320
- } catch (error) {
321
- const rollbackErrors = [];
322
- if (stageFile) await rm(stageFile, { force: true }).catch(() => {
323
- });
324
- await rm(targetSessionDir, { recursive: true, force: true }).catch(() => {
325
- });
326
- if (sourceDirMoved) {
327
- try {
328
- await mkdir(dirname(sourceSessionDir), { recursive: true });
329
- await rename(backupDir, sourceSessionDir);
330
- } catch (restoreErr) {
331
- rollbackErrors.push(restoreErr);
240
+ const sourceLoc = persistence.locate({ id: cleanSessionId, cwd: header.cwd });
241
+ const targetLoc = persistence.locate({ id: cleanSessionId, cwd: targetPath });
242
+ if (!sourceLoc || !targetLoc || !sourceLoc.path || !targetLoc.path) {
243
+ throw new Error("\u6301\u4E45\u5316\u540E\u7AEF\u65E0\u6CD5\u5B9A\u4F4D\u4F1A\u8BDD\u5DE5\u4EF6\u8DEF\u5F84\u3002");
332
244
  }
333
- }
334
- if (header) {
335
- registry.headers?.set(cleanSessionId, header);
336
- }
337
- if (previousPath === void 0) registry.sessionPaths?.delete(cleanSessionId);
338
- else registry.sessionPaths?.set(cleanSessionId, previousPath);
339
- restoreInvalidSessionState(registry.invalidSessionPaths, cleanSessionId, previousInvalidPath);
340
- if (!wasMissing) registry.missingSessionPaths?.delete(cleanSessionId);
341
- else registry.missingSessionPaths?.add(cleanSessionId);
342
- for (const ws of attemptedSources) {
343
- if (rawWorkspaceSessionIds(ws).includes(cleanSessionId)) continue;
245
+ const sourceLogPath = sourceLoc.path;
246
+ const targetLogPath = targetLoc.path;
247
+ const sourceSessionDir = dirname(sourceLogPath);
248
+ const targetSessionDir = dirname(targetLogPath);
249
+ let targetOccupied = false;
344
250
  try {
345
- await ws.attachSession(cleanSessionId);
346
- if (!rawWorkspaceSessionIds(ws).includes(cleanSessionId)) {
347
- throw new Error(`\u539F\u5DE5\u4F5C\u533A\u672A\u6062\u590D\u4F1A\u8BDD\u5173\u8054\uFF1A${ws.id}`);
251
+ await stat(targetLogPath);
252
+ targetOccupied = true;
253
+ } catch {
254
+ }
255
+ if (targetOccupied) {
256
+ throw new Error(`\u76EE\u6807\u5DE5\u4F5C\u533A\u5DF2\u5B58\u5728\u540C\u540D\u4F1A\u8BDD\u5DE5\u4EF6\uFF0C\u62D2\u7EDD\u8986\u76D6: ${targetLogPath}`);
257
+ }
258
+ const persistenceRoot = persistence.root ?? persistence.config?.root;
259
+ const backupRoot = persistenceRoot ? join(dirname(resolve(persistenceRoot)), "dsham-move-backup") : join(dirname(sourceSessionDir), ".dsham-move-backup");
260
+ await mkdir(backupRoot, { recursive: true });
261
+ const safeSessionName = encodeURIComponent(cleanSessionId).replace(/%/g, "~");
262
+ const backupDir = join(backupRoot, `${safeSessionName}-${process.pid}-${Date.now()}`);
263
+ const isZstd = sourceLogPath.endsWith(".zstd");
264
+ const sourceBytes = await readFile(sourceLogPath);
265
+ const newBytes = rewriteSessionArtifactCwd(sourceBytes, targetPath, isZstd);
266
+ if (isZstd) {
267
+ const f0 = zlib.zstdDecompressSync(newBytes);
268
+ const f0Obj = JSON.parse(f0.toString("utf8").split("\n")[0]);
269
+ if (f0Obj.id !== cleanSessionId || f0Obj.cwd !== targetPath) {
270
+ throw new Error("\u8FC1\u79FB\u524D\u6821\u9A8C\u5931\u8D25\uFF1A\u6570\u636E\u6539\u5199\u9A8C\u8BC1\u672A\u901A\u8FC7\u3002");
348
271
  }
349
- } catch (restoreError) {
350
- rollbackErrors.push(restoreError);
351
272
  }
352
- }
353
- if (!rollbackErrors.length && targetAttached && !targetHadSession && rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
273
+ requireReleasedSession();
274
+ const targetHadSession = rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId);
275
+ const previousPath = registry.sessionPaths?.get(cleanSessionId);
276
+ const previousInvalidPath = getInvalidSessionState(registry.invalidSessionPaths, cleanSessionId);
277
+ const wasMissing = registry.missingSessionPaths?.has(cleanSessionId) ?? false;
278
+ const attemptedSources = [];
279
+ let targetAttached = false;
280
+ let stageFile = null;
281
+ let sourceDirMoved = false;
354
282
  try {
355
- await targetWorkspace.detachSession(cleanSessionId);
356
- } catch (restoreError) {
357
- rollbackErrors.push(restoreError);
283
+ await rename(sourceSessionDir, backupDir);
284
+ sourceDirMoved = true;
285
+ await mkdir(targetSessionDir, { recursive: true });
286
+ stageFile = join(targetSessionDir, `.stage-${process.pid}-${Date.now()}`);
287
+ await writeFile(stageFile, newBytes);
288
+ await rename(stageFile, targetLogPath);
289
+ stageFile = null;
290
+ const readbackBytes = await readFile(targetLogPath);
291
+ if (readbackBytes.length === 0) throw new Error("\u76EE\u6807\u5199\u5165\u5DE5\u4EF6\u4E3A\u7A7A");
292
+ const targetHeader = { ...header, cwd: targetPath };
293
+ registry.sessionPaths?.set(cleanSessionId, targetPath);
294
+ registry.headers?.set(cleanSessionId, targetHeader);
295
+ registry.invalidSessionPaths?.delete(cleanSessionId);
296
+ await targetWorkspace.attachSession(cleanSessionId);
297
+ if (!rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
298
+ throw new Error("\u76EE\u6807\u5DE5\u4F5C\u533A\u672A\u4FDD\u7559\u4F1A\u8BDD\u5173\u8054\uFF0C\u5DF2\u53D6\u6D88\u79FB\u52A8\u3002");
299
+ }
300
+ targetAttached = true;
301
+ for (const ws of sourceWorkspaces) {
302
+ attemptedSources.push(ws);
303
+ await ws.detachSession(cleanSessionId);
304
+ }
305
+ if (ctx.sessionProjectionCache && typeof ctx.sessionProjectionCache.coldSnapshot === "function") {
306
+ try {
307
+ if (ctx.sessionProjectionCache.coldSnapshot.length === 1) {
308
+ await ctx.sessionProjectionCache.coldSnapshot(cleanSessionId);
309
+ } else if (persistence && typeof persistence.open === "function") {
310
+ const readHandle = await persistence.open(cleanSessionId, "read");
311
+ try {
312
+ const { events } = typeof readHandle.read === "function" ? await readHandle.read(0) : { events: [] };
313
+ const coldMeta = readHandle.header ?? targetHeader;
314
+ const inherited = readHandle.inheritedEventCount ?? 0;
315
+ await ctx.sessionProjectionCache.coldSnapshot(
316
+ coldMeta,
317
+ inherited,
318
+ events ?? []
319
+ );
320
+ } finally {
321
+ await readHandle.close();
322
+ }
323
+ }
324
+ } catch (err) {
325
+ ctx.logger?.warn?.(`archive-manager: post-move coldSnapshot failed: ${String(err)}`);
326
+ }
327
+ }
328
+ } catch (error) {
329
+ const rollbackErrors = [];
330
+ if (stageFile) await rm(stageFile, { force: true }).catch(() => {
331
+ });
332
+ await rm(targetSessionDir, { recursive: true, force: true }).catch(() => {
333
+ });
334
+ if (sourceDirMoved) {
335
+ try {
336
+ await mkdir(dirname(sourceSessionDir), { recursive: true });
337
+ await rename(backupDir, sourceSessionDir);
338
+ } catch (restoreErr) {
339
+ rollbackErrors.push(restoreErr);
340
+ }
341
+ }
342
+ if (header) {
343
+ registry.headers?.set(cleanSessionId, header);
344
+ }
345
+ if (previousPath === void 0) registry.sessionPaths?.delete(cleanSessionId);
346
+ else registry.sessionPaths?.set(cleanSessionId, previousPath);
347
+ restoreInvalidSessionState(registry.invalidSessionPaths, cleanSessionId, previousInvalidPath);
348
+ if (!wasMissing) registry.missingSessionPaths?.delete(cleanSessionId);
349
+ else registry.missingSessionPaths?.add(cleanSessionId);
350
+ for (const ws of attemptedSources) {
351
+ if (rawWorkspaceSessionIds(ws).includes(cleanSessionId)) continue;
352
+ try {
353
+ await ws.attachSession(cleanSessionId);
354
+ if (!rawWorkspaceSessionIds(ws).includes(cleanSessionId)) {
355
+ throw new Error(`\u539F\u5DE5\u4F5C\u533A\u672A\u6062\u590D\u4F1A\u8BDD\u5173\u8054\uFF1A${ws.id}`);
356
+ }
357
+ } catch (restoreError) {
358
+ rollbackErrors.push(restoreError);
359
+ }
360
+ }
361
+ if (!rollbackErrors.length && targetAttached && !targetHadSession && rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
362
+ try {
363
+ await targetWorkspace.detachSession(cleanSessionId);
364
+ } catch (restoreError) {
365
+ rollbackErrors.push(restoreError);
366
+ }
367
+ }
368
+ if (rollbackErrors.length) {
369
+ throw new AggregateError([error, ...rollbackErrors], `\u7269\u7406\u79FB\u52A8\u5931\u8D25\uFF0C\u4E14\u672A\u80FD\u5B8C\u6574\u6062\u590D\u5DE5\u4EF6\u6216\u5DE5\u4F5C\u533A\u5173\u8054\uFF1A${String(error)}`);
370
+ }
371
+ throw error;
358
372
  }
359
- }
360
- if (rollbackErrors.length) {
361
- throw new AggregateError([error, ...rollbackErrors], `\u7269\u7406\u79FB\u52A8\u5931\u8D25\uFF0C\u4E14\u672A\u80FD\u5B8C\u6574\u6062\u590D\u5DE5\u4EF6\u6216\u5DE5\u4F5C\u533A\u5173\u8054\uFF1A${String(error)}`);
362
- }
363
- throw error;
364
- }
365
- await rm(backupDir, { recursive: true, force: true }).catch(() => {
366
- });
367
- return {
368
- ok: true,
369
- moved: true,
370
- alreadyCwd: false,
371
- sessionId: cleanSessionId,
372
- toWorkspaceId: cleanTargetWsId,
373
- toWorkspaceTitle: targetWorkspace.title || cleanTargetWsId,
374
- toWorkspacePath: targetPath
375
- };
373
+ await rm(backupDir, { recursive: true, force: true }).catch(() => {
374
+ });
375
+ return {
376
+ ok: true,
377
+ moved: true,
378
+ alreadyCwd: false,
379
+ sessionId: cleanSessionId,
380
+ toWorkspaceId: cleanTargetWsId,
381
+ toWorkspaceTitle: targetWorkspace.title || cleanTargetWsId,
382
+ toWorkspacePath: targetPath
383
+ };
384
+ },
385
+ { targetPath }
386
+ );
376
387
  }
377
388
  export {
378
389
  moveSessionToWorkspace,
package/lib/workspace.js CHANGED
@@ -1194,6 +1194,8 @@ var ArchiveWorkspaceRegistry = class extends WorkspaceRegistry {
1194
1194
  sessionProjectionCache: this.ctx.get("sessionProjectionCache"),
1195
1195
  sessions: this.ctx.get("sessions"),
1196
1196
  agents: this.ctx.get("agents"),
1197
+ sessionController: this.ctx.get("sessionController"),
1198
+ workingDirectory: this.ctx.get("workingDirectory"),
1197
1199
  logger: this.ctx.logger
1198
1200
  },
1199
1201
  sessionId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@michengai/dsh-archive-manager",
3
- "version": "1.4.2",
3
+ "version": "1.5.1",
4
4
  "description": "归档、恢复、收藏和永久删除会话,并诊断损坏的会话日志。 · Archive, restore, favorite, and permanently delete sessions, and diagnose damaged session logs.",
5
5
  "type": "module",
6
6
  "packageManager": "pnpm@11.22.0",
@@ -74,32 +74,32 @@
74
74
  }
75
75
  },
76
76
  "devDependencies": {
77
- "@deepseek-ai/cordis": "4.2.0-alpha.1",
78
- "@deepseek-ai/dsh-api-gateway": "0.2.3-alpha.2",
79
- "@deepseek-ai/dsh-client-connection": "0.2.3-alpha.2",
80
- "@deepseek-ai/dsh-client-locale": "0.2.3-alpha.2",
81
- "@deepseek-ai/dsh-client-store": "0.2.3-alpha.2",
82
- "@deepseek-ai/dsh-client-ui-conversation": "0.2.3-alpha.2",
83
- "@deepseek-ai/dsh-client-ui-primitives": "0.2.3-alpha.2",
84
- "@deepseek-ai/dsh-client-ui-renderer": "0.2.3-alpha.2",
85
- "@deepseek-ai/dsh-client-ui-sidebar": "0.2.3-alpha.2",
86
- "@deepseek-ai/dsh-client-ui-slots": "0.2.3-alpha.2",
87
- "@deepseek-ai/dsh-client-ui-workspace": "0.2.3-alpha.2",
88
- "@deepseek-ai/dsh-error": "0.2.3-alpha.2",
89
- "@deepseek-ai/dsh-host-webserver": "0.2.3-alpha.2",
90
- "@deepseek-ai/dsh-scope": "0.2.3-alpha.2",
91
- "@deepseek-ai/dsh-session": "0.2.3-alpha.2",
92
- "@deepseek-ai/dsh-session-format-catalog": "0.2.3-alpha.2",
93
- "@deepseek-ai/dsh-session-persistence": "0.2.3-alpha.2",
94
- "@deepseek-ai/dsh-session-projection": "0.2.3-alpha.2",
95
- "@deepseek-ai/dsh-session-projection-cache": "0.2.3-alpha.2",
96
- "@deepseek-ai/dsh-spill": "0.2.3-alpha.2",
97
- "@deepseek-ai/dsh-spill-local": "0.2.3-alpha.2",
98
- "@deepseek-ai/dsh-storage": "0.2.3-alpha.2",
99
- "@deepseek-ai/dsh-storage-domain": "0.2.3-alpha.2",
100
- "@deepseek-ai/dsh-typert-protocol": "0.2.3-alpha.2",
101
- "@deepseek-ai/dsh-typert-registry": "0.2.3-alpha.2",
102
- "@deepseek-ai/dsh-workspace": "0.2.3-alpha.2",
77
+ "@deepseek-ai/cordis": "4.2.0-alpha.2",
78
+ "@deepseek-ai/dsh-api-gateway": "0.2.3-alpha.3",
79
+ "@deepseek-ai/dsh-client-connection": "0.2.3-alpha.3",
80
+ "@deepseek-ai/dsh-client-locale": "0.2.3-alpha.3",
81
+ "@deepseek-ai/dsh-client-store": "0.2.3-alpha.3",
82
+ "@deepseek-ai/dsh-client-ui-conversation": "0.2.3-alpha.3",
83
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.3-alpha.3",
84
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.3-alpha.3",
85
+ "@deepseek-ai/dsh-client-ui-sidebar": "0.2.3-alpha.3",
86
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.3-alpha.3",
87
+ "@deepseek-ai/dsh-client-ui-workspace": "0.2.3-alpha.3",
88
+ "@deepseek-ai/dsh-error": "0.2.3-alpha.3",
89
+ "@deepseek-ai/dsh-host-webserver": "0.2.3-alpha.3",
90
+ "@deepseek-ai/dsh-scope": "0.2.3-alpha.3",
91
+ "@deepseek-ai/dsh-session": "0.2.3-alpha.3",
92
+ "@deepseek-ai/dsh-session-format-catalog": "0.2.3-alpha.3",
93
+ "@deepseek-ai/dsh-session-persistence": "0.2.3-alpha.3",
94
+ "@deepseek-ai/dsh-session-projection": "0.2.3-alpha.3",
95
+ "@deepseek-ai/dsh-session-projection-cache": "0.2.3-alpha.3",
96
+ "@deepseek-ai/dsh-spill": "0.2.3-alpha.3",
97
+ "@deepseek-ai/dsh-spill-local": "0.2.3-alpha.3",
98
+ "@deepseek-ai/dsh-storage": "0.2.3-alpha.3",
99
+ "@deepseek-ai/dsh-storage-domain": "0.2.3-alpha.3",
100
+ "@deepseek-ai/dsh-typert-protocol": "0.2.3-alpha.3",
101
+ "@deepseek-ai/dsh-typert-registry": "0.2.3-alpha.3",
102
+ "@deepseek-ai/dsh-workspace": "0.2.3-alpha.3",
103
103
  "@types/node": "^22.20.4",
104
104
  "@types/react": "^18.3.31",
105
105
  "@types/react-dom": "^18.0.0",