@njuptlzf/agent-chat-server 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,437 @@
1
+ import { createHash, createHmac } from "node:crypto";
2
+ import { isIP } from "node:net";
3
+ import type { FileEntry } from "@earendil-works/pi-coding-agent";
4
+
5
+ /**
6
+ * 会话历史冷热分层阶段 1–2 的内部接缝(不进公开导出)。
7
+ *
8
+ * 对象存储只放 `history.entries` 正文;SQLite 仍是索引与元数据的唯一真相源。
9
+ * 这里刻意不引入云 SDK:B5 的硬约束是本地零云依赖,且各家 S3 兼容实现
10
+ * 的差异(virtual-host、拒 aws-chunked)用 SDK 反而要额外关开关。Node 内置
11
+ * fetch + crypto 的 SigV4 足够覆盖 put/get 两个动作,依赖面一动不动。
12
+ */
13
+
14
+ /** 正文对象的最小读写面。测试注入内存实现,生产走 S3 兼容 HTTP。 */
15
+ export interface HistoryArchiveStore {
16
+ put(key: string, body: string): Promise<void>;
17
+ get(key: string): Promise<string | null>;
18
+ }
19
+
20
+ export interface ArchiveSweepOptions {
21
+ idleDays: number;
22
+ batchSize: number;
23
+ }
24
+
25
+ export interface ArchiveSweepReport {
26
+ scanned: number;
27
+ archived: number;
28
+ skipped: number;
29
+ failed: number;
30
+ }
31
+
32
+ /** 真正做归档/恢复的 store 能力;ServerDeps 上的可选字段用这个类型收口。 */
33
+ export interface HistoryArchiveCapable {
34
+ archiveIdle(options: ArchiveSweepOptions): Promise<ArchiveSweepReport>;
35
+ restore(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined>;
36
+ }
37
+
38
+ export interface HistoryArchiveConfig {
39
+ store: HistoryArchiveStore;
40
+ idleDays: number;
41
+ batchSize: number;
42
+ intervalMs: number;
43
+ /** 阶段 2:热模式开关;关闭时 save/load 与阶段 1 完全一致。 */
44
+ hot: boolean;
45
+ cacheEntries: number;
46
+ cacheBytes: number;
47
+ }
48
+
49
+ /** 对象存储读不到/校验不过:只有已归档会话会踩到,本地会话不受影响。 */
50
+ export class HistoryArchiveUnavailableError extends Error {
51
+ constructor(message: string) {
52
+ super(message);
53
+ this.name = "HistoryArchiveUnavailableError";
54
+ }
55
+ }
56
+
57
+ const EMPTY_SHA256 = createHash("sha256").update("").digest("hex");
58
+ const REQUEST_TIMEOUT_MS = 10_000;
59
+ const MAX_ATTEMPTS = 3;
60
+
61
+ function sha256Hex(data: string | Uint8Array): string {
62
+ return createHash("sha256").update(data).digest("hex");
63
+ }
64
+
65
+ function errorText(err: unknown): string {
66
+ return err instanceof Error ? err.message : String(err);
67
+ }
68
+
69
+ /** 内容寻址:key 就是正文字节的 sha256,重跑天然得到同一个 key。 */
70
+ export function archiveKeyFor(body: string): string {
71
+ return `archive/${sha256Hex(body)}.json`;
72
+ }
73
+
74
+ /** 取回时按 key 里的 hash 验正文,损坏对象不会被写回 SQLite。 */
75
+ export function verifyArchiveObject(key: string, body: string): boolean {
76
+ const match = /^archive\/([a-f0-9]{64})\.json$/.exec(key);
77
+ return match !== null && match[1] === sha256Hex(body);
78
+ }
79
+
80
+ /** 缓存按会话索引,避免两条会话正文相同时共享一个缓存项导致失效串台。 */
81
+ export function sessionCacheKey(userId: string, scope: string, sessionId: string): string {
82
+ return `${userId}\u0000${scope}\u0000${sessionId}`;
83
+ }
84
+
85
+ export interface HistoryBodyCacheStats {
86
+ entries: number;
87
+ bytes: number;
88
+ hits: number;
89
+ misses: number;
90
+ evictions: number;
91
+ }
92
+
93
+ interface CachedBody {
94
+ key: string;
95
+ body: string;
96
+ bytes: number;
97
+ }
98
+
99
+ /**
100
+ * 进程内 LRU。条数与字节双上限;get 命中把项移到队尾,set 先删旧项再插入。
101
+ * 这不持久化:进程重启 / 缓存全丢后仍从对象存储验 hash 恢复(阶段 2 验收)。
102
+ */
103
+ export class HistoryBodyCache {
104
+ private readonly map = new Map<string, CachedBody>();
105
+ private bytes = 0;
106
+ private hits = 0;
107
+ private misses = 0;
108
+ private evictions = 0;
109
+
110
+ constructor(
111
+ private readonly maxEntries = 500,
112
+ private readonly maxBytes = 64 * 1024 * 1024,
113
+ private readonly onEvict?: (sessionKey: string, reason: "count" | "bytes" | "replace") => void,
114
+ ) {}
115
+
116
+ get(sessionKey: string, archiveKey: string): string | undefined {
117
+ const found = this.map.get(sessionKey);
118
+ if (!found || found.key !== archiveKey) {
119
+ if (found) this.remove(sessionKey);
120
+ this.misses++;
121
+ return undefined;
122
+ }
123
+ this.map.delete(sessionKey);
124
+ this.map.set(sessionKey, found);
125
+ this.hits++;
126
+ return found.body;
127
+ }
128
+
129
+ set(sessionKey: string, archiveKey: string, body: string): void {
130
+ const replaced = this.remove(sessionKey);
131
+ if (replaced) this.onEvict?.(sessionKey, "replace");
132
+ const bytes = Buffer.byteLength(body, "utf8");
133
+ this.map.set(sessionKey, { key: archiveKey, body, bytes });
134
+ this.bytes += bytes;
135
+ while (this.map.size > this.maxEntries || this.bytes > this.maxBytes) {
136
+ const oldest = this.map.keys().next();
137
+ if (oldest.done) break;
138
+ const reason = this.map.size > this.maxEntries ? "count" : "bytes";
139
+ this.remove(oldest.value);
140
+ this.evictions++;
141
+ this.onEvict?.(oldest.value, reason);
142
+ }
143
+ }
144
+
145
+ delete(sessionKey: string): void {
146
+ this.remove(sessionKey);
147
+ }
148
+
149
+ clear(): void {
150
+ this.map.clear();
151
+ this.bytes = 0;
152
+ }
153
+
154
+ stats(): HistoryBodyCacheStats {
155
+ return { entries: this.map.size, bytes: this.bytes, hits: this.hits, misses: this.misses, evictions: this.evictions };
156
+ }
157
+
158
+ private remove(sessionKey: string): CachedBody | undefined {
159
+ const found = this.map.get(sessionKey);
160
+ if (!found) return undefined;
161
+ this.map.delete(sessionKey);
162
+ this.bytes -= found.bytes;
163
+ return found;
164
+ }
165
+ }
166
+
167
+ /** key 布局:path-style 走 endpoint/bucket/key,virtual-host 走 bucket.endpoint/key。 */
168
+ export function archiveObjectUrl(endpoint: URL, bucket: string, key: string, pathStyle: boolean): URL {
169
+ const url = new URL(endpoint.href);
170
+ const encoded = key.split("/").map((part) => encodeURIComponent(part)).join("/");
171
+ const base = url.pathname.replace(/\/+$/, "");
172
+ if (pathStyle) {
173
+ url.pathname = `${base}/${bucket}/${encoded}`;
174
+ } else {
175
+ url.hostname = `${bucket}.${url.hostname}`;
176
+ url.pathname = `${base}/${encoded}`;
177
+ }
178
+ return url;
179
+ }
180
+
181
+ /** 测试替身:对象留在进程内,不碰网络。 */
182
+ export function createInMemoryHistoryArchiveStore(): HistoryArchiveStore & { objects: Map<string, string> } {
183
+ const objects = new Map<string, string>();
184
+ return {
185
+ objects,
186
+ async put(key, body) {
187
+ objects.set(key, body);
188
+ },
189
+ async get(key) {
190
+ return objects.get(key) ?? null;
191
+ },
192
+ };
193
+ }
194
+
195
+ /** S3 兼容客户端:只实现 put/get,SigV4 手工签名,无第三方依赖。 */
196
+ export class S3HistoryArchiveStore implements HistoryArchiveStore {
197
+ private readonly endpoint: URL;
198
+ private readonly credential: { accessKeyId: string; secretAccessKey: string; region: string };
199
+
200
+ constructor(opts: {
201
+ endpoint: URL;
202
+ bucket: string;
203
+ accessKeyId: string;
204
+ secretAccessKey: string;
205
+ region: string;
206
+ pathStyle: boolean;
207
+ }) {
208
+ this.endpoint = opts.endpoint;
209
+ this.credential = {
210
+ accessKeyId: opts.accessKeyId,
211
+ secretAccessKey: opts.secretAccessKey,
212
+ region: opts.region,
213
+ };
214
+ this.bucket = opts.bucket;
215
+ this.pathStyle = opts.pathStyle;
216
+ }
217
+
218
+ private readonly bucket: string;
219
+ private readonly pathStyle: boolean;
220
+
221
+ private url(key: string): URL {
222
+ return archiveObjectUrl(this.endpoint, this.bucket, key, this.pathStyle);
223
+ }
224
+
225
+ private headers(method: "GET" | "PUT" | "HEAD", url: URL, payloadHash: string): Record<string, string> {
226
+ const amzDate = new Date().toISOString().replace(/[:-]|\.\d{3}/g, "");
227
+ const dateStamp = amzDate.slice(0, 8);
228
+ const headers: Record<string, string> = {
229
+ host: url.host,
230
+ "x-amz-content-sha256": payloadHash,
231
+ "x-amz-date": amzDate,
232
+ };
233
+ const signed = Object.keys(headers).sort();
234
+ const canonicalHeaders = signed.map((name) => `${name}:${headers[name]!.trim()}\n`).join("");
235
+ const canonicalRequest = [
236
+ method,
237
+ url.pathname,
238
+ url.search.replace(/^\?/, ""),
239
+ canonicalHeaders,
240
+ signed.join(";"),
241
+ payloadHash,
242
+ ].join("\n");
243
+ const scope = `${dateStamp}/${this.credential.region}/s3/aws4_request`;
244
+ const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256Hex(canonicalRequest)].join("\n");
245
+ const kDate = createHmac("sha256", `AWS4${this.credential.secretAccessKey}`).update(dateStamp).digest();
246
+ const kRegion = createHmac("sha256", kDate).update(this.credential.region).digest();
247
+ const kService = createHmac("sha256", kRegion).update("s3").digest();
248
+ const kSigning = createHmac("sha256", kService).update("aws4_request").digest();
249
+ const signature = createHmac("sha256", kSigning).update(stringToSign).digest("hex");
250
+ headers.authorization =
251
+ `AWS4-HMAC-SHA256 Credential=${this.credential.accessKeyId}/${scope}, ` +
252
+ `SignedHeaders=${signed.join(";")}, Signature=${signature}`;
253
+ return headers;
254
+ }
255
+
256
+ private async withRetry<T>(label: string, fn: () => Promise<T>): Promise<T> {
257
+ let last: unknown;
258
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
259
+ try {
260
+ return await fn();
261
+ } catch (err) {
262
+ last = err;
263
+ }
264
+ }
265
+ throw new HistoryArchiveUnavailableError(`${label} failed after ${MAX_ATTEMPTS} attempts: ${errorText(last)}`);
266
+ }
267
+
268
+ /** 自检桶:存在即放行,不存在则创建。409(已被本账号占用)也视为就绪。 */
269
+ async ensureBucket(): Promise<void> {
270
+ const url = new URL(this.endpoint.href);
271
+ const base = url.pathname.replace(/\/+$/, "");
272
+ // virtual-host 必须把桶名并入 hostname(该布局下 endpoint 根域会拒 path-style 请求),与 archiveObjectUrl 同一口径。
273
+ if (this.pathStyle) {
274
+ url.pathname = `${base}/${this.bucket}`;
275
+ } else {
276
+ url.hostname = `${this.bucket}.${url.hostname}`;
277
+ url.pathname = base || "/";
278
+ }
279
+ const probe = await fetch(url, {
280
+ method: "HEAD",
281
+ headers: this.headers("HEAD", url, EMPTY_SHA256),
282
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
283
+ });
284
+ if (probe.status === 200) return;
285
+ if (probe.status !== 404) throw new Error(`bucket check failed: HTTP ${probe.status}`);
286
+ const created = await fetch(url, {
287
+ method: "PUT",
288
+ headers: this.headers("PUT", url, EMPTY_SHA256),
289
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
290
+ });
291
+ if (![200, 201, 204, 409].includes(created.status)) {
292
+ throw new Error(`bucket creation failed: HTTP ${created.status}`);
293
+ }
294
+ }
295
+
296
+ async put(key: string, body: string): Promise<void> {
297
+ const bytes = Buffer.from(body, "utf8");
298
+ await this.withRetry(`archive put ${key}`, async () => {
299
+ const url = this.url(key);
300
+ const res = await fetch(url, {
301
+ method: "PUT",
302
+ headers: this.headers("PUT", url, sha256Hex(bytes)),
303
+ body: bytes,
304
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
305
+ });
306
+ if (!res.ok) throw new Error(`HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
307
+ await res.arrayBuffer();
308
+ });
309
+ }
310
+
311
+ async get(key: string): Promise<string | null> {
312
+ return this.withRetry(`archive get ${key}`, async () => {
313
+ const url = this.url(key);
314
+ const res = await fetch(url, {
315
+ method: "GET",
316
+ headers: this.headers("GET", url, EMPTY_SHA256),
317
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
318
+ });
319
+ if (res.status === 404) return null;
320
+ if (!res.ok) throw new Error(`HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
321
+ return Buffer.from(await res.arrayBuffer()).toString("utf8");
322
+ });
323
+ }
324
+ }
325
+
326
+ const ARCHIVE_ENV_KEYS = [
327
+ "HISTORY_ARCHIVE_ENDPOINT",
328
+ "HISTORY_ARCHIVE_REGION",
329
+ "HISTORY_ARCHIVE_BUCKET",
330
+ "HISTORY_ARCHIVE_ACCESS_KEY_ID",
331
+ "HISTORY_ARCHIVE_SECRET_ACCESS_KEY",
332
+ "HISTORY_ARCHIVE_PATH_STYLE",
333
+ "HISTORY_ARCHIVE_IDLE_DAYS",
334
+ "HISTORY_ARCHIVE_BATCH_SIZE",
335
+ "HISTORY_ARCHIVE_INTERVAL_MS",
336
+ "HISTORY_ARCHIVE_HOT_ENABLED",
337
+ "HISTORY_ARCHIVE_HOT_CACHE_ENTRIES",
338
+ "HISTORY_ARCHIVE_HOT_CACHE_BYTES",
339
+ ] as const;
340
+
341
+ function positiveInt(env: NodeJS.ProcessEnv, name: string, fallback: number, min = 1): number {
342
+ const raw = env[name];
343
+ if (raw === undefined || raw === "") return fallback;
344
+ const value = Number(raw);
345
+ if (!Number.isInteger(value) || value < min) {
346
+ throw new Error(`[history-archive] ${name} must be an integer >= ${min}, got "${raw}"`);
347
+ }
348
+ return value;
349
+ }
350
+
351
+ function booleanEnv(env: NodeJS.ProcessEnv, name: string, fallback: boolean): boolean {
352
+ const raw = env[name];
353
+ if (raw === undefined || raw === "") return fallback;
354
+ if (raw === "true") return true;
355
+ if (raw === "false") return false;
356
+ throw new Error(`[history-archive] ${name} must be "true" or "false", got "${raw}"`);
357
+ }
358
+
359
+ /**
360
+ * 启动时集中校验。全部未设置 = 归档功能关闭(本地零云依赖的默认形态);
361
+ * 只要出现任一归档变量,必需项缺失就 fail-fast,不静默半开。
362
+ */
363
+ export function loadHistoryArchiveConfig(env: NodeJS.ProcessEnv = process.env): HistoryArchiveConfig | undefined {
364
+ const enabled = ARCHIVE_ENV_KEYS.some((key) => env[key] !== undefined && env[key] !== "");
365
+ if (!enabled) return undefined;
366
+
367
+ const required = [
368
+ "HISTORY_ARCHIVE_ENDPOINT",
369
+ "HISTORY_ARCHIVE_BUCKET",
370
+ "HISTORY_ARCHIVE_ACCESS_KEY_ID",
371
+ "HISTORY_ARCHIVE_SECRET_ACCESS_KEY",
372
+ ] as const;
373
+ const missing = required.filter((key) => !env[key]);
374
+ if (missing.length > 0) {
375
+ throw new Error(`[history-archive] enabled but missing: ${missing.join(", ")}`);
376
+ }
377
+
378
+ let endpoint: URL;
379
+ try {
380
+ endpoint = new URL(env.HISTORY_ARCHIVE_ENDPOINT!);
381
+ } catch {
382
+ throw new Error(`[history-archive] HISTORY_ARCHIVE_ENDPOINT must be an absolute URL`);
383
+ }
384
+ if (!["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
385
+ throw new Error(`[history-archive] HISTORY_ARCHIVE_ENDPOINT must be a bare http(s) URL without credentials/query/hash`);
386
+ }
387
+ const bucket = env.HISTORY_ARCHIVE_BUCKET!;
388
+ if (bucket.includes("/")) throw new Error(`[history-archive] HISTORY_ARCHIVE_BUCKET must not contain "/"`);
389
+ const pathStyle = booleanEnv(env, "HISTORY_ARCHIVE_PATH_STYLE", false);
390
+ // URL 的 hostname 不接受 `bucket.127.0.0.1` 这种伪域名;IP 端点必须显式走 path-style。
391
+ if (!pathStyle && isIP(endpoint.hostname) > 0) {
392
+ throw new Error(`[history-archive] virtual-host needs a hostname; set HISTORY_ARCHIVE_PATH_STYLE=true for IP endpoints`);
393
+ }
394
+
395
+ return {
396
+ store: new S3HistoryArchiveStore({
397
+ endpoint,
398
+ bucket,
399
+ accessKeyId: env.HISTORY_ARCHIVE_ACCESS_KEY_ID!,
400
+ secretAccessKey: env.HISTORY_ARCHIVE_SECRET_ACCESS_KEY!,
401
+ region: env.HISTORY_ARCHIVE_REGION || "us-east-1",
402
+ pathStyle,
403
+ }),
404
+ idleDays: positiveInt(env, "HISTORY_ARCHIVE_IDLE_DAYS", 30),
405
+ batchSize: positiveInt(env, "HISTORY_ARCHIVE_BATCH_SIZE", 50),
406
+ intervalMs: positiveInt(env, "HISTORY_ARCHIVE_INTERVAL_MS", 3_600_000, 1_000),
407
+ hot: booleanEnv(env, "HISTORY_ARCHIVE_HOT_ENABLED", false),
408
+ cacheEntries: positiveInt(env, "HISTORY_ARCHIVE_HOT_CACHE_ENTRIES", 500),
409
+ cacheBytes: positiveInt(env, "HISTORY_ARCHIVE_HOT_CACHE_BYTES", 64 * 1024 * 1024),
410
+ };
411
+ }
412
+
413
+ export interface HistoryArchiver {
414
+ sweep(): Promise<ArchiveSweepReport>;
415
+ stop(): void;
416
+ }
417
+
418
+ /** 后台定时器:只在配置了归档时创建;unref 避免它成为测试/CLI 的 open handle。 */
419
+ export function startHistoryArchiver(
420
+ archive: HistoryArchiveCapable,
421
+ config: Pick<HistoryArchiveConfig, "idleDays" | "batchSize" | "intervalMs">,
422
+ ): HistoryArchiver {
423
+ let stopped = false;
424
+ const sweep = () => archive.archiveIdle({ idleDays: config.idleDays, batchSize: config.batchSize });
425
+ const timer = setInterval(() => {
426
+ if (stopped) return;
427
+ void sweep().catch((err) => console.warn("[history-archive] sweep failed:", errorText(err)));
428
+ }, config.intervalMs);
429
+ timer.unref?.();
430
+ return {
431
+ sweep,
432
+ stop() {
433
+ stopped = true;
434
+ clearInterval(timer);
435
+ },
436
+ };
437
+ }
package/src/main.ts CHANGED
@@ -12,6 +12,7 @@ import { describeComponents } from "./components.ts";
12
12
  import { createModelRuntime } from "./session.ts";
13
13
  import { createAdminAuth, createJwtAuth, insecureHeaderAuth } from "./stores.ts";
14
14
  import { openDatabase, SqliteAccountState, SqliteAudit, SqliteBilling, SqliteCheckpointStore, SqliteHistoryStore, SqliteMembership, SqliteMemberPool, SqliteLedger, SqliteRunLog } from "./sqlite-stores.ts";
15
+ import { HistoryBodyCache, loadHistoryArchiveConfig, startHistoryArchiver } from "./history-archive.ts";
15
16
  import { billingUsage } from "./usage-report.ts";
16
17
 
17
18
  const productDir = process.env.PRODUCT_DIR;
@@ -49,6 +50,18 @@ const toolFactory = await loadToolFactory(product);
49
50
 
50
51
  // Pre-scope rows belong to the qualification this deployment used to serve.
51
52
  const db = openDatabase(path.join(dataDir, "agent-chat.db"), product.defaultQual, product.defaultPersona);
53
+ // 阶段 1:归档配置全缺 = 功能关闭;出现任一变量则 load 内部 fail-fast。
54
+ const archiveConfig = loadHistoryArchiveConfig();
55
+ if (archiveConfig) {
56
+ console.log(
57
+ `[agent-chat] history archive: idle ${archiveConfig.idleDays}d · batch ${archiveConfig.batchSize} · every ${archiveConfig.intervalMs}ms · hot ${archiveConfig.hot ? "on" : "off"}`,
58
+ );
59
+ }
60
+ const historyCache = new HistoryBodyCache(archiveConfig?.cacheEntries, archiveConfig?.cacheBytes);
61
+ const history = new SqliteHistoryStore(db, archiveConfig?.store, {
62
+ hot: archiveConfig?.hot ?? false,
63
+ cache: historyCache,
64
+ });
52
65
  // S4:产品 Store 由产品仓自己装配(manifest server.assembly 动态 import,形状不对即启动失败)。
53
66
  const productAssembly = await loadProductAssembly(product);
54
67
 
@@ -114,7 +127,8 @@ const deps = {
114
127
  mcpConfig,
115
128
  personaConfig,
116
129
  toolFactory,
117
- history: new SqliteHistoryStore(db),
130
+ history,
131
+ historyArchive: archiveConfig ? history : undefined,
118
132
  ledger: new SqliteLedger(db, product.manifest.agent.limits?.dailyTokenQuota),
119
133
  // 统一成本模型:启动期已校验 models.json 声明,这里装配成本表供 settle 折算 CU。
120
134
  // 全局倍率兜底(无逐模型声明时用)来自 manifest,默认 1 CU/千 token。
@@ -142,6 +156,8 @@ const deps = {
142
156
  await initProductRoutes(productRoutes, deps);
143
157
 
144
158
  const server = createChatServer(deps);
159
+ const historyArchiver = archiveConfig ? startHistoryArchiver(history, archiveConfig) : undefined;
160
+ server.on("close", () => historyArchiver?.stop());
145
161
 
146
162
  const port = Number(process.env.PORT ?? 8787);
147
163
  server.listen(port, () => {
package/src/server.ts CHANGED
@@ -24,6 +24,7 @@ import type { JobSpec, RunOutcome, RunSpec } from "./orchestrator/run-spec.ts";
24
24
  import { createTaskflowEngine } from "./orchestrator/engines/taskflow.ts";
25
25
  import type { CheckpointStore } from "./checkpoint-store.ts";
26
26
  import { persistCheckpoints, resumeFrom as loadResumeFrom } from "./checkpoint-store.ts";
27
+ import type { HistoryArchiveCapable } from "./history-archive.ts";
27
28
  import { toRunSpec } from "./flows.ts";
28
29
 
29
30
  /**
@@ -87,6 +88,8 @@ export interface ServerDeps {
87
88
  modelCooldown?: CooldownRegistry;
88
89
  toolFactory: (ctx: ToolContext) => unknown[];
89
90
  history: HistoryStore;
91
+ /** 对象存储归档能力。omitted ⇒ 恢复端点 503;主链只在配置归档时装配。 */
92
+ historyArchive?: HistoryArchiveCapable;
90
93
  /**
91
94
  * 预留-结算额度账本(M-14 W3)。替换了旧的 `QuotaGate.check/record`:
92
95
  * 先占位再开跑,并发下不会超发(旧模型实测超发 140%)。
@@ -2415,6 +2418,36 @@ export function createChatServer(deps: ServerDeps): Server {
2415
2418
  if (kept !== entries && scope !== undefined) await deps.history.save(auth.userId, scope, body.sessionId, kept);
2416
2419
  return sendJson(res, 200, { sessionId: body.sessionId, messages: toHistoryMessages(kept) });
2417
2420
  }
2421
+ if (req.method === "POST" && url.pathname === "/api/history/restore") {
2422
+ const auth = await deps.authenticate(req);
2423
+ if (!auth) return deny401(deps, req, res);
2424
+ if (!deps.historyArchive) {
2425
+ return sendError(res, 503, "internal", "history archive is not configured");
2426
+ }
2427
+ let body: { sessionId?: unknown };
2428
+ try {
2429
+ body = (await readJson(req)) as typeof body;
2430
+ } catch {
2431
+ return sendError(res, 400, "bad_request", "body must be valid JSON under 64KB");
2432
+ }
2433
+ if (typeof body.sessionId !== "string" || !SESSION_ID.test(body.sessionId)) {
2434
+ return sendError(res, 400, "bad_request", "expected {sessionId}");
2435
+ }
2436
+ // 与编辑路径同一条并发闸:run 末尾会整块写回历史,恢复不能插在中间。
2437
+ if (running.has(`${auth.userId}\u0000${body.sessionId}`)) {
2438
+ return sendError(res, 409, "bad_request", "this session already has a run in progress");
2439
+ }
2440
+ const scope = await deps.history.scopeOf(auth.userId, body.sessionId);
2441
+ if (scope === undefined) return sendError(res, 404, "not_found", "session not found");
2442
+ try {
2443
+ const entries = await deps.historyArchive.restore(auth.userId, scope, body.sessionId);
2444
+ if (!entries) return sendError(res, 404, "not_found", "session not found");
2445
+ return sendJson(res, 200, { sessionId: body.sessionId, messages: toHistoryMessages(entries) });
2446
+ } catch (err) {
2447
+ // 对象存储不可达/校验失败只让这条恢复请求失败,不影响其它会话的在线读写。
2448
+ return sendError(res, 503, "internal", err instanceof Error ? err.message : "history restore failed");
2449
+ }
2450
+ }
2418
2451
  if (req.method === "POST" && url.pathname === "/api/chat") return await handleChat(req, res);
2419
2452
  if (req.method === "POST" && url.pathname === "/api/suggestions") {
2420
2453
  const auth = await deps.authenticate(req);
package/src/session.ts CHANGED
@@ -571,6 +571,36 @@ export function sharedProfileMismatchWarning(
571
571
  + "用户偏好不会在 scope 之间共享。请改用支持该能力的 provider,或移除该依赖声明。";
572
572
  }
573
573
 
574
+ /**
575
+ * The single source of truth for memory root paths. Pure: no fs, no env, no cwd.
576
+ *
577
+ * Two disjoint roots per tenant:
578
+ * - `storageRoot` — one per (user, scope), dies with the qualification/session;
579
+ * - `sharedRoot` — one per user, dies only on account deletion.
580
+ * Siblings, never nested: deleting a qualification must not delete user identity.
581
+ * The scope key falls back through memoryScopeKey → qual → "default"; callers
582
+ * must not re-implement that order (job-scoped sessions pass an explicit key).
583
+ * `qual` is the second fallback so callers pass both and own no precedence logic.
584
+ *
585
+ * Path layers, so nobody has to count the two directory names:
586
+ * - `tenants/` is the HOST layer — one root per (user, scope), plus one per user
587
+ * for the shared profile. The host allocates and erases it.
588
+ * - `memory/` (under a tenant root) is the PROVIDER's internal layout, which
589
+ * this host neither knows nor asserts.
590
+ */
591
+ export function resolveMemoryRoots(
592
+ dataDir: string,
593
+ userId: string,
594
+ memoryScopeKey: string | undefined,
595
+ qual: string | undefined,
596
+ ): { storageRoot: string; sharedRoot: string } {
597
+ const scope = memoryScopeKey || qual || "default";
598
+ return {
599
+ storageRoot: path.join(dataDir, "tenants", userId, scope),
600
+ sharedRoot: path.join(dataDir, "tenants", userId, "profile"),
601
+ };
602
+ }
603
+
574
604
  /**
575
605
  * Build a pi session locked down for multi-user serving:
576
606
  * - no built-in tools (no bash / read / write / edit), verified by test
@@ -716,8 +746,12 @@ export async function createProductSession(opts: CreateProductSessionOptions): P
716
746
  // The host owns the roots, so it must materialise them before open(). The
717
747
  // old built-in created parents lazily on write; hermes uses mkdtemp under
718
748
  // storageRoot and expects the host-allocated directory to already exist.
719
- const storageRoot = path.join(opts.dataDir, "memory", opts.userId, opts.memoryScopeKey || opts.qual || "default");
720
- const sharedRoot = path.join(opts.dataDir, "memory", opts.userId, "profile");
749
+ const { storageRoot, sharedRoot } = resolveMemoryRoots(
750
+ opts.dataDir,
751
+ opts.userId,
752
+ opts.memoryScopeKey,
753
+ opts.qual,
754
+ );
721
755
  if (memoryProvider) {
722
756
  mkdirSync(storageRoot, { recursive: true });
723
757
  mkdirSync(sharedRoot, { recursive: true });