@michengai/dsh-archive-manager 1.4.2 → 1.5.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.
- package/CHANGELOG.md +7 -0
- package/CHANGELOG.zh-CN.md +7 -0
- package/lib/client.js +6 -6
- package/lib/host-install.js +18 -1
- package/lib/session-lifecycle.js +160 -0
- package/lib/session-move.js +165 -157
- package/lib/workspace.js +2 -0
- package/package.json +1 -1
package/lib/host-install.js
CHANGED
|
@@ -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
|
-
|
|
25
|
+
try {
|
|
26
|
+
uninstallLifecycle();
|
|
27
|
+
} finally {
|
|
28
|
+
uninstallWorkspace();
|
|
29
|
+
}
|
|
13
30
|
}
|
|
14
31
|
};
|
|
15
32
|
try {
|
|
@@ -0,0 +1,160 @@
|
|
|
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
|
+
runtime.moving.add(sessionId);
|
|
111
|
+
let failure = void 0;
|
|
112
|
+
let result;
|
|
113
|
+
try {
|
|
114
|
+
await handle.dispose();
|
|
115
|
+
result = await operation();
|
|
116
|
+
} catch (error) {
|
|
117
|
+
failure = error;
|
|
118
|
+
throw error;
|
|
119
|
+
} finally {
|
|
120
|
+
runtime.handles.delete(sessionId);
|
|
121
|
+
try {
|
|
122
|
+
if (typeof controller?.resolveAgent === "function") {
|
|
123
|
+
const restored = await migrationContext.run(
|
|
124
|
+
runtime,
|
|
125
|
+
() => controller.resolveAgent(sessionId)
|
|
126
|
+
);
|
|
127
|
+
if (restored?.error) {
|
|
128
|
+
throw restored.error;
|
|
129
|
+
}
|
|
130
|
+
runtime.moving.delete(sessionId);
|
|
131
|
+
if (!failure && options?.targetPath && restored?.agent) {
|
|
132
|
+
const workingDirectory = ctx.workingDirectory ?? (typeof ctx.get === "function" ? ctx.get("workingDirectory") : void 0);
|
|
133
|
+
if (typeof workingDirectory?.set === "function") {
|
|
134
|
+
await migrationContext.run(
|
|
135
|
+
runtime,
|
|
136
|
+
() => workingDirectory.set(restored.agent, options.targetPath)
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (!failure) {
|
|
143
|
+
ctx.logger?.warn?.(
|
|
144
|
+
`[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)}`
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
} finally {
|
|
148
|
+
runtime.moving.delete(sessionId);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (failure) throw failure;
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
export {
|
|
155
|
+
installSessionLifecycle,
|
|
156
|
+
lifecycleFor,
|
|
157
|
+
migrationContext,
|
|
158
|
+
migrationInProgressError,
|
|
159
|
+
withReleasedSession
|
|
160
|
+
};
|
package/lib/session-move.js
CHANGED
|
@@ -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) {
|
|
@@ -142,23 +143,23 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
|
|
|
142
143
|
return isOther && rawWorkspaceSessionIds(ws).includes(cleanSessionId);
|
|
143
144
|
});
|
|
144
145
|
if (currentNormalizedCwd && targetNormalizedCwd && currentNormalizedCwd === targetNormalizedCwd) {
|
|
145
|
-
const
|
|
146
|
-
const
|
|
147
|
-
const
|
|
148
|
-
const
|
|
149
|
-
const
|
|
146
|
+
const targetHadSession = rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId);
|
|
147
|
+
const previousPath = registry.sessionPaths?.get(cleanSessionId);
|
|
148
|
+
const previousInvalidPath = getInvalidSessionState(registry.invalidSessionPaths, cleanSessionId);
|
|
149
|
+
const wasMissing = registry.missingSessionPaths?.has(cleanSessionId);
|
|
150
|
+
const attemptedSources = [];
|
|
150
151
|
try {
|
|
151
152
|
await targetWorkspace.attachSession(cleanSessionId);
|
|
152
153
|
if (!rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
|
|
153
154
|
throw new Error("\u76EE\u6807\u5DE5\u4F5C\u533A\u672A\u4FDD\u7559\u4F1A\u8BDD\u5173\u8054\uFF0C\u5DF2\u53D6\u6D88\u79FB\u52A8\u3002");
|
|
154
155
|
}
|
|
155
156
|
for (const ws of sourceWorkspaces) {
|
|
156
|
-
|
|
157
|
+
attemptedSources.push(ws);
|
|
157
158
|
await ws.detachSession(cleanSessionId);
|
|
158
159
|
}
|
|
159
160
|
} catch (error) {
|
|
160
161
|
const rollbackErrors = [];
|
|
161
|
-
for (const ws of
|
|
162
|
+
for (const ws of attemptedSources) {
|
|
162
163
|
if (rawWorkspaceSessionIds(ws).includes(cleanSessionId)) continue;
|
|
163
164
|
try {
|
|
164
165
|
await ws.attachSession(cleanSessionId);
|
|
@@ -169,7 +170,7 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
|
|
|
169
170
|
rollbackErrors.push(restoreError);
|
|
170
171
|
}
|
|
171
172
|
}
|
|
172
|
-
if (!rollbackErrors.length && !
|
|
173
|
+
if (!rollbackErrors.length && !targetHadSession && rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
|
|
173
174
|
try {
|
|
174
175
|
await targetWorkspace.detachSession(cleanSessionId);
|
|
175
176
|
} catch (restoreError) {
|
|
@@ -179,10 +180,10 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
|
|
|
179
180
|
if (rollbackErrors.length) {
|
|
180
181
|
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
182
|
}
|
|
182
|
-
if (
|
|
183
|
-
else registry.sessionPaths?.set(cleanSessionId,
|
|
184
|
-
restoreInvalidSessionState(registry.invalidSessionPaths, cleanSessionId,
|
|
185
|
-
if (!
|
|
183
|
+
if (previousPath === void 0) registry.sessionPaths?.delete(cleanSessionId);
|
|
184
|
+
else registry.sessionPaths?.set(cleanSessionId, previousPath);
|
|
185
|
+
restoreInvalidSessionState(registry.invalidSessionPaths, cleanSessionId, previousInvalidPath);
|
|
186
|
+
if (!wasMissing) registry.missingSessionPaths?.delete(cleanSessionId);
|
|
186
187
|
else registry.missingSessionPaths?.add(cleanSessionId);
|
|
187
188
|
throw error;
|
|
188
189
|
}
|
|
@@ -220,159 +221,166 @@ async function moveSessionToWorkspace(ctx, sessionId, targetWorkspaceId) {
|
|
|
220
221
|
toWorkspacePath: targetPath
|
|
221
222
|
};
|
|
222
223
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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
|
-
}
|
|
224
|
+
return withReleasedSession(
|
|
225
|
+
ctx,
|
|
226
|
+
cleanSessionId,
|
|
227
|
+
async () => {
|
|
228
|
+
const requireReleasedSession = () => {
|
|
229
|
+
if (ctx.sessions?.get?.(cleanSessionId) || ctx.agents?.get?.(cleanSessionId)) {
|
|
230
|
+
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
231
|
}
|
|
316
|
-
}
|
|
317
|
-
|
|
232
|
+
};
|
|
233
|
+
requireReleasedSession();
|
|
234
|
+
if (!persistence || typeof persistence.locate !== "function") {
|
|
235
|
+
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
236
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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);
|
|
237
|
+
const sourceLoc = persistence.locate({ id: cleanSessionId, cwd: header.cwd });
|
|
238
|
+
const targetLoc = persistence.locate({ id: cleanSessionId, cwd: targetPath });
|
|
239
|
+
if (!sourceLoc || !targetLoc || !sourceLoc.path || !targetLoc.path) {
|
|
240
|
+
throw new Error("\u6301\u4E45\u5316\u540E\u7AEF\u65E0\u6CD5\u5B9A\u4F4D\u4F1A\u8BDD\u5DE5\u4EF6\u8DEF\u5F84\u3002");
|
|
332
241
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
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;
|
|
242
|
+
const sourceLogPath = sourceLoc.path;
|
|
243
|
+
const targetLogPath = targetLoc.path;
|
|
244
|
+
const sourceSessionDir = dirname(sourceLogPath);
|
|
245
|
+
const targetSessionDir = dirname(targetLogPath);
|
|
246
|
+
let targetOccupied = false;
|
|
344
247
|
try {
|
|
345
|
-
await
|
|
346
|
-
|
|
347
|
-
|
|
248
|
+
await stat(targetLogPath);
|
|
249
|
+
targetOccupied = true;
|
|
250
|
+
} catch {
|
|
251
|
+
}
|
|
252
|
+
if (targetOccupied) {
|
|
253
|
+
throw new Error(`\u76EE\u6807\u5DE5\u4F5C\u533A\u5DF2\u5B58\u5728\u540C\u540D\u4F1A\u8BDD\u5DE5\u4EF6\uFF0C\u62D2\u7EDD\u8986\u76D6: ${targetLogPath}`);
|
|
254
|
+
}
|
|
255
|
+
const persistenceRoot = persistence.root ?? persistence.config?.root;
|
|
256
|
+
const backupRoot = persistenceRoot ? join(dirname(resolve(persistenceRoot)), "dsham-move-backup") : join(dirname(sourceSessionDir), ".dsham-move-backup");
|
|
257
|
+
await mkdir(backupRoot, { recursive: true });
|
|
258
|
+
const safeSessionName = encodeURIComponent(cleanSessionId).replace(/%/g, "~");
|
|
259
|
+
const backupDir = join(backupRoot, `${safeSessionName}-${process.pid}-${Date.now()}`);
|
|
260
|
+
const isZstd = sourceLogPath.endsWith(".zstd");
|
|
261
|
+
const sourceBytes = await readFile(sourceLogPath);
|
|
262
|
+
const newBytes = rewriteSessionArtifactCwd(sourceBytes, targetPath, isZstd);
|
|
263
|
+
if (isZstd) {
|
|
264
|
+
const f0 = zlib.zstdDecompressSync(newBytes);
|
|
265
|
+
const f0Obj = JSON.parse(f0.toString("utf8").split("\n")[0]);
|
|
266
|
+
if (f0Obj.id !== cleanSessionId || f0Obj.cwd !== targetPath) {
|
|
267
|
+
throw new Error("\u8FC1\u79FB\u524D\u6821\u9A8C\u5931\u8D25\uFF1A\u6570\u636E\u6539\u5199\u9A8C\u8BC1\u672A\u901A\u8FC7\u3002");
|
|
348
268
|
}
|
|
349
|
-
} catch (restoreError) {
|
|
350
|
-
rollbackErrors.push(restoreError);
|
|
351
269
|
}
|
|
352
|
-
|
|
353
|
-
|
|
270
|
+
requireReleasedSession();
|
|
271
|
+
const targetHadSession = rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId);
|
|
272
|
+
const previousPath = registry.sessionPaths?.get(cleanSessionId);
|
|
273
|
+
const previousInvalidPath = getInvalidSessionState(registry.invalidSessionPaths, cleanSessionId);
|
|
274
|
+
const wasMissing = registry.missingSessionPaths?.has(cleanSessionId) ?? false;
|
|
275
|
+
const attemptedSources = [];
|
|
276
|
+
let targetAttached = false;
|
|
277
|
+
let stageFile = null;
|
|
278
|
+
let sourceDirMoved = false;
|
|
354
279
|
try {
|
|
355
|
-
await
|
|
356
|
-
|
|
357
|
-
|
|
280
|
+
await rename(sourceSessionDir, backupDir);
|
|
281
|
+
sourceDirMoved = true;
|
|
282
|
+
await mkdir(targetSessionDir, { recursive: true });
|
|
283
|
+
stageFile = join(targetSessionDir, `.stage-${process.pid}-${Date.now()}`);
|
|
284
|
+
await writeFile(stageFile, newBytes);
|
|
285
|
+
await rename(stageFile, targetLogPath);
|
|
286
|
+
stageFile = null;
|
|
287
|
+
const readbackBytes = await readFile(targetLogPath);
|
|
288
|
+
if (readbackBytes.length === 0) throw new Error("\u76EE\u6807\u5199\u5165\u5DE5\u4EF6\u4E3A\u7A7A");
|
|
289
|
+
const targetHeader = { ...header, cwd: targetPath };
|
|
290
|
+
registry.sessionPaths?.set(cleanSessionId, targetPath);
|
|
291
|
+
registry.headers?.set(cleanSessionId, targetHeader);
|
|
292
|
+
registry.invalidSessionPaths?.delete(cleanSessionId);
|
|
293
|
+
await targetWorkspace.attachSession(cleanSessionId);
|
|
294
|
+
if (!rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
|
|
295
|
+
throw new Error("\u76EE\u6807\u5DE5\u4F5C\u533A\u672A\u4FDD\u7559\u4F1A\u8BDD\u5173\u8054\uFF0C\u5DF2\u53D6\u6D88\u79FB\u52A8\u3002");
|
|
296
|
+
}
|
|
297
|
+
targetAttached = true;
|
|
298
|
+
for (const ws of sourceWorkspaces) {
|
|
299
|
+
attemptedSources.push(ws);
|
|
300
|
+
await ws.detachSession(cleanSessionId);
|
|
301
|
+
}
|
|
302
|
+
if (ctx.sessionProjectionCache && typeof ctx.sessionProjectionCache.coldSnapshot === "function") {
|
|
303
|
+
try {
|
|
304
|
+
if (ctx.sessionProjectionCache.coldSnapshot.length === 1) {
|
|
305
|
+
await ctx.sessionProjectionCache.coldSnapshot(cleanSessionId);
|
|
306
|
+
} else if (persistence && typeof persistence.open === "function") {
|
|
307
|
+
const readHandle = await persistence.open(cleanSessionId, "read");
|
|
308
|
+
try {
|
|
309
|
+
const { events } = typeof readHandle.read === "function" ? await readHandle.read(0) : { events: [] };
|
|
310
|
+
const coldMeta = readHandle.header ?? targetHeader;
|
|
311
|
+
const inherited = readHandle.inheritedEventCount ?? 0;
|
|
312
|
+
await ctx.sessionProjectionCache.coldSnapshot(
|
|
313
|
+
coldMeta,
|
|
314
|
+
inherited,
|
|
315
|
+
events ?? []
|
|
316
|
+
);
|
|
317
|
+
} finally {
|
|
318
|
+
await readHandle.close();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
} catch (err) {
|
|
322
|
+
ctx.logger?.warn?.(`archive-manager: post-move coldSnapshot failed: ${String(err)}`);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
} catch (error) {
|
|
326
|
+
const rollbackErrors = [];
|
|
327
|
+
if (stageFile) await rm(stageFile, { force: true }).catch(() => {
|
|
328
|
+
});
|
|
329
|
+
await rm(targetSessionDir, { recursive: true, force: true }).catch(() => {
|
|
330
|
+
});
|
|
331
|
+
if (sourceDirMoved) {
|
|
332
|
+
try {
|
|
333
|
+
await mkdir(dirname(sourceSessionDir), { recursive: true });
|
|
334
|
+
await rename(backupDir, sourceSessionDir);
|
|
335
|
+
} catch (restoreErr) {
|
|
336
|
+
rollbackErrors.push(restoreErr);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (header) {
|
|
340
|
+
registry.headers?.set(cleanSessionId, header);
|
|
341
|
+
}
|
|
342
|
+
if (previousPath === void 0) registry.sessionPaths?.delete(cleanSessionId);
|
|
343
|
+
else registry.sessionPaths?.set(cleanSessionId, previousPath);
|
|
344
|
+
restoreInvalidSessionState(registry.invalidSessionPaths, cleanSessionId, previousInvalidPath);
|
|
345
|
+
if (!wasMissing) registry.missingSessionPaths?.delete(cleanSessionId);
|
|
346
|
+
else registry.missingSessionPaths?.add(cleanSessionId);
|
|
347
|
+
for (const ws of attemptedSources) {
|
|
348
|
+
if (rawWorkspaceSessionIds(ws).includes(cleanSessionId)) continue;
|
|
349
|
+
try {
|
|
350
|
+
await ws.attachSession(cleanSessionId);
|
|
351
|
+
if (!rawWorkspaceSessionIds(ws).includes(cleanSessionId)) {
|
|
352
|
+
throw new Error(`\u539F\u5DE5\u4F5C\u533A\u672A\u6062\u590D\u4F1A\u8BDD\u5173\u8054\uFF1A${ws.id}`);
|
|
353
|
+
}
|
|
354
|
+
} catch (restoreError) {
|
|
355
|
+
rollbackErrors.push(restoreError);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (!rollbackErrors.length && targetAttached && !targetHadSession && rawWorkspaceSessionIds(targetWorkspace).includes(cleanSessionId)) {
|
|
359
|
+
try {
|
|
360
|
+
await targetWorkspace.detachSession(cleanSessionId);
|
|
361
|
+
} catch (restoreError) {
|
|
362
|
+
rollbackErrors.push(restoreError);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (rollbackErrors.length) {
|
|
366
|
+
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)}`);
|
|
367
|
+
}
|
|
368
|
+
throw error;
|
|
358
369
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
toWorkspaceTitle: targetWorkspace.title || cleanTargetWsId,
|
|
374
|
-
toWorkspacePath: targetPath
|
|
375
|
-
};
|
|
370
|
+
await rm(backupDir, { recursive: true, force: true }).catch(() => {
|
|
371
|
+
});
|
|
372
|
+
return {
|
|
373
|
+
ok: true,
|
|
374
|
+
moved: true,
|
|
375
|
+
alreadyCwd: false,
|
|
376
|
+
sessionId: cleanSessionId,
|
|
377
|
+
toWorkspaceId: cleanTargetWsId,
|
|
378
|
+
toWorkspaceTitle: targetWorkspace.title || cleanTargetWsId,
|
|
379
|
+
toWorkspacePath: targetPath
|
|
380
|
+
};
|
|
381
|
+
},
|
|
382
|
+
{ targetPath }
|
|
383
|
+
);
|
|
376
384
|
}
|
|
377
385
|
export {
|
|
378
386
|
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.
|
|
3
|
+
"version": "1.5.0",
|
|
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",
|