@deepseek-ai/dsh-session-persistence-jsonl 0.2.1-alpha.2 → 0.2.1-alpha.3

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/README.i18n.yaml CHANGED
@@ -21,14 +21,14 @@
21
21
  en: 37c10302bbbde268
22
22
  zh: 3d5c027bac868efd
23
23
  /deepseek-ai-dsh-session-persistence-jsonl/use-this-package/minimal-configuration:
24
- en: 22e8c3b2da45edff
25
- zh: d9effd892b514520
24
+ en: b6c2f0f11f2fa9cf
25
+ zh: 9fac03fcbe5bbad4
26
26
  /deepseek-ai-dsh-session-persistence-jsonl/use-this-package/on-disk-layout:
27
27
  en: e20cf32540d7c785
28
28
  zh: 67e182529e9211ca
29
29
  /deepseek-ai-dsh-session-persistence-jsonl/use-this-package/durability-and-crash-semantics:
30
- en: 1eaa87736cac029b
31
- zh: 26224e8889786d69
30
+ en: 96498792672f6d50
31
+ zh: d767a9c69dced889
32
32
  /deepseek-ai-dsh-session-persistence-jsonl/use-this-package/reading-the-logs:
33
33
  en: 3e53fc90a486d373
34
34
  zh: 00e6c6e65c56629e
@@ -36,8 +36,8 @@
36
36
  en: a35407bb25671e7e
37
37
  zh: 6a00f9510c85adcb
38
38
  /deepseek-ai-dsh-session-persistence-jsonl/understand-the-implementation/design-concept:
39
- en: b69d4565a11b6f02
40
- zh: c8309690fc931f8d
39
+ en: a422bd0f74a5b31a
40
+ zh: edc47e9530c87f67
41
41
  /deepseek-ai-dsh-session-persistence-jsonl/understand-the-implementation/physical-encoding:
42
42
  en: 5aaf80115840318f
43
43
  zh: 0b0fb2b2e085a111
@@ -63,8 +63,8 @@
63
63
  en: 53ce4da7ce68d21c
64
64
  zh: 10f40bc354100f77
65
65
  /deepseek-ai-dsh-session-persistence-jsonl/known-limitations-and-deferred-work:
66
- en: e6343e8ad3f6fb71
67
- zh: fe632c9711e7921b
66
+ en: c46c91a811abc547
67
+ zh: 41fb942d4e61e544
68
68
  /deepseek-ai-dsh-session-persistence-jsonl/known-limitations-and-deferred-work/dev-note:
69
69
  en: e67f633dc6fe7773
70
70
  zh: 3bb0c20c93f16f98
package/README.md CHANGED
@@ -46,6 +46,7 @@ Choose this backend when consumers benefit from one artifact per session — nav
46
46
  |---|---|---|
47
47
  | `root` | required | Root directory for all session files |
48
48
  | `compression` | `'zstd'` | Physical encoding: `'zstd'` checksummed frames, or `'none'` newline-delimited UTF-8 text |
49
+ | `listConcurrency` | `3` | Maximum directory, header, and stat reads in flight, shared by every concurrent listing of this backend |
49
50
 
50
51
  Live-event write batching is not configuration: the batching window is the seam's internal scheduling policy inside each write handle.
51
52
 
@@ -77,6 +78,8 @@ A session is materialized lazily: `create(header)` writes nothing and returns th
77
78
 
78
79
  The current-generation scanner applies the current codec owner’s structural admission checks before recoverable-tail handling. Retired required PTC tags and `request/header.header.system` refuse the file even after an earlier malformed row; recovery never truncates them as ordinary damaged tail data.
79
80
 
81
+ Unloading the backend waits for the consumer unloads it triggers through `sessionPersistence` injection before removing live-event listeners and draining and closing remaining handles. Consumers must register cleanup in that injecting scope; unrelated scopes and explicit Session or handle closure have their own lifetimes. Programmatic mounting uses the plugin namespace (`import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'`) with `ctx.plugin`; access storage through `ctx.sessionPersistence`.
82
+
80
83
  ### Reading the logs
81
84
 
82
85
  Materialized `stat` and `list` snapshots include the format catalog's header classification as `formatStatus`, alongside the translated logical `header`. A read-only preparation leaves the selected historical version unchanged; the status becomes `current` after publication of the successor. Unmaterialized pending Sessions omit `formatStatus`.
@@ -101,7 +104,7 @@ This section explains the physical encoding and write path; the observable contr
101
104
 
102
105
  ### Design concept
103
106
 
104
- The backend owns its complete storage runtime (`src/storage.ts`): `JsonlSessionHandle` carries the per-handle mutation chain, the routed live-event buffer with its fixed batching window and single-flight drain, monotonic reads, and idempotent close; a tracker holds the in-process single-writer claims, the open-handle set teardown sweeps, and the created-but-unmaterialized pending sessions the backend's own session listeners route into. Historical body reads share one per-session Decode/Migrate preparation, and a bounded revision-keyed memo lets an immediate observe-to-resume handoff reuse that parse; the backend deep-freezes each event graph once before memoization, so later handle reads reuse it without copying or freezing. Only a write open publishes the prepared successor. The package deliberately exposes only its default plugin export plus configuration types — the concrete class is not a named export, so consumers couple to `ctx.sessionPersistence`, and the shared seam suites (`runPersistenceContract`/`runLiveWritePathContract`) pin its observable behavior. Physical revisions combine device, inode, size, and nanosecond timestamps for the preparation memo, stable-read retries, and publication checks. Historical public revisions add a SHA-256 fingerprint of sorted selected paths and their physical revisions; lock files and retained unselected generations do not contribute.
107
+ The backend owns its complete storage runtime (`src/storage.ts`): `JsonlSessionHandle` carries the per-handle mutation chain, the routed live-event buffer with its fixed batching window and single-flight drain, monotonic reads, and idempotent close; a tracker holds the in-process single-writer claims, the open-handle set teardown sweeps, and the created-but-unmaterialized pending sessions the backend's own session listeners route into. Historical body reads share one per-session Decode/Migrate preparation, and a bounded revision-keyed memo lets an immediate observe-to-resume handoff reuse that parse; the backend deep-freezes each event graph once before memoization, so later handle reads reuse it without copying or freezing. Only a write open publishes the prepared successor. The package exposes plugin exports and configuration types — the concrete class is private, so consumers couple to `ctx.sessionPersistence`, and the shared seam suites (`runPersistenceContract`/`runLiveWritePathContract`) pin its observable behavior. Physical revisions combine device, inode, size, and nanosecond timestamps for the preparation memo, stable-read retries, and publication checks. Historical public revisions add a SHA-256 fingerprint of sorted selected paths and their physical revisions; lock files and retained unselected generations do not contribute.
105
108
 
106
109
  ### Physical encoding
107
110
 
@@ -163,6 +166,7 @@ These limits define when this backend is a poor fit or needs special operational
163
166
  - **Compressed files are not directly line-readable** — use the backend to load them, or select `compression: 'none'` before writing a fresh root when external line readers are required.
164
167
  - **Nothing deletes session files** — logs accumulate under `root` until removed externally; the seam has no deletion API.
165
168
  - **One live writer per session** — the write-handle claim excludes a second writer inside the owning backend instance, and a kernel lock (non-blocking `flock(2)` on `session.lock`; on Windows a named kernel semaphore derived from that path, with no filesystem footprint) excludes every other instance and process; the lock is taken at write-open of an existing artifact and, for a created session, only right before its first materializing write, so an unmaterialized session leaves no filesystem footprint. A crashed holder's lock dies with its process, so its session is writable again immediately, while a live-but-wedged holder blocks writers until its process exits (on POSIX, removing the lock file forfeits that exclusion; release itself never removes it). Advisory `flock` is unreliable on some network filesystems (NFSv3), and the Windows semaphore name is per login session.
169
+ - **Concurrent root disposal is not ordered** — Cordis can remove already-disposing consumers from its registry before the provider can join their cleanup. Dependency ordering here covers consumer unloads triggered by removing this provider.
166
170
  - **POSIX materialization requires hard-link support** — first append uses `link()` so same-id races fail instead of overwriting a committed log; Windows uses write-through rename without replacement.
167
171
  - **POSIX writes require the matching prebuilt system addon** — [`node-addon-system`](../../../native/system/README.md) supplies asynchronous flock without consumer-side compilation. A missing addon rejects write ownership; Windows retains its semaphore implementation.
168
172
 
package/README.zh.md CHANGED
@@ -46,6 +46,7 @@ kind: "package-reference"
46
46
  |---|---|---|
47
47
  | `root` | 必填 | 所有会话文件的根目录 |
48
48
  | `compression` | `'zstd'` | 物理编码:`'zstd'` 带校验和帧,或 `'none'` 换行分隔 UTF-8 文本 |
49
+ | `listConcurrency` | `3` | 同时进行的目录、header 与 stat 读取上限,由该后端所有并发的列举共用 |
49
50
 
50
51
  实时事件的写入批处理不是配置:批处理窗口是该 seam 在每个写句柄内部的调度策略。
51
52
 
@@ -77,6 +78,8 @@ kind: "package-reference"
77
78
 
78
79
  当前代际扫描器在处理可恢复尾部之前,执行当前编解码器所有者的结构准入检查。已退役的必需 PTC 标签与 `request/header.header.system` 即使出现在较早的畸形行之后也会导致文件被拒绝;恢复绝不将它们作为普通损坏尾部数据截断。
79
80
 
81
+ 卸载后端时,会先等待经由 `sessionPersistence` 注入所触发的消费者卸载,再移除实时事件监听器、排空并关闭剩余句柄。消费者必须在该注入作用域中注册清理;无依赖关系的作用域,以及显式关闭的 Session 或句柄,各自遵循其生命周期。通过代码挂载时,使用插件命名空间(`import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'`)调用 `ctx.plugin`,并通过 `ctx.sessionPersistence` 访问存储。
82
+
80
83
  ### 读取日志
81
84
 
82
85
  已实体化的 `stat` 与 `list` 快照在转换后的逻辑 `header` 之外,通过 `formatStatus` 保留格式 catalog 的头部分类。只读准备不会改变所选历史版本;发布后继之后,状态才变为 `current`。尚未实体化的待定 Session 省略 `formatStatus`。
@@ -101,7 +104,7 @@ kind: "package-reference"
101
104
 
102
105
  ### 设计理念
103
106
 
104
- 该后端拥有自己完整的存储运行时(`src/storage.ts`):`JsonlSessionHandle` 承载逐句柄修改链、带固定批处理窗口与 single-flight 排空的已路由实时事件缓冲、单调读取与幂等 close;一个 tracker 持有进程内单写者认领、teardown 清扫所遍历的打开句柄集合,以及后端自己的会话监听器所路由进的已创建但未实体化待定会话。历史正文读取共享每个 Session 唯一的一次 Decode/Migrate preparation,按 revision 为键的有界 memo 让紧接的观察到恢复交接复用该解析;backend 在 memo 化前只对每个 event graph 深度冻结一次,因此后续 handle read 无需复制或再次冻结。只有写 open 才发布准备好的后继。本包有意只暴露默认插件导出与配置类型——具体类不是具名导出,因此消费方只耦合 `ctx.sessionPersistence`,其可观察行为由共享 seam 测试套件(`runPersistenceContract`/`runLiveWritePathContract`)钉住。物理修订号组合 device、inode、size 与纳秒时间戳,供准备缓存、稳定读取重试及发布检查使用。历史格式的公开修订号还加入所选路径排序后及其物理修订号的 SHA-256 指纹;锁文件与保留但未被选中的代际不参与计算。
107
+ 该后端拥有自己完整的存储运行时(`src/storage.ts`):`JsonlSessionHandle` 承载逐句柄修改链、带固定批处理窗口与 single-flight 排空的已路由实时事件缓冲、单调读取与幂等 close;一个 tracker 持有进程内单写者认领、teardown 清扫所遍历的打开句柄集合,以及后端自己的会话监听器所路由进的已创建但未实体化待定会话。历史正文读取共享每个 Session 唯一的一次 Decode/Migrate preparation,按 revision 为键的有界 memo 让紧接的观察到恢复交接复用该解析;backend 在 memo 化前只对每个 event graph 深度冻结一次,因此后续 handle read 无需复制或再次冻结。只有写 open 才发布准备好的后继。本包暴露插件导出与配置类型——具体类是私有的,因此消费方只耦合 `ctx.sessionPersistence`,其可观察行为由共享 seam 测试套件(`runPersistenceContract`/`runLiveWritePathContract`)钉住。物理修订号组合 device、inode、size 与纳秒时间戳,供准备缓存、稳定读取重试及发布检查使用。历史格式的公开修订号还加入所选路径排序后及其物理修订号的 SHA-256 指纹;锁文件与保留但未被选中的代际不参与计算。
105
108
 
106
109
  ### 物理编码
107
110
 
@@ -163,6 +166,7 @@ JSONL 存储不修改实时请求前缀。只有重建历史、当前 envelope
163
166
  - **压缩文件不能直接按行读取**——使用后端加载;或在写入新根前选择 `compression: 'none'`,供外部行读取方使用。
164
167
  - **不删除会话文件**——日志在 `root` 下累积,直到外部移除;seam 无删除接口。
165
168
  - **每会话一个活动写入方**——写句柄认领在所属后端实例内排除第二个写入方,内核锁(`session.lock` 上的非阻塞 `flock(2)`;Windows 上为由该路径派生的命名内核信号量,零文件系统足迹)排除其他所有实例与进程;锁在以写模式打开既有产物时立即获取,新建会话则仅在首次实体化写入之前获取,因此未实体化的会话不留任何文件系统足迹。崩溃持有者的锁随其进程消亡,会话立即可再写入,而活着但卡死的持有者会阻塞写入方直到其进程退出(POSIX 上删除锁文件即放弃该排他;释放本身从不删除它)。咨询式 `flock` 在部分网络文件系统(NFSv3)上不可靠,Windows 信号量名按登录会话隔离。
169
+ - **根作用域的并发卸载不保证顺序**——Cordis 可能在提供者等待消费者清理前,已将正在卸载的消费者移出注册表。此处的依赖顺序仅覆盖移除该提供者所触发的消费者卸载。
166
170
  - **POSIX 实体化需要硬链接支持**——第一次 append 使用 `link()`,使同 id 竞态失败而不覆盖已提交日志;Windows 使用无替换 write-through rename。
167
171
  - **POSIX 写入需要匹配的预编译系统 addon**——[`node-addon-system`](../../../native/system/README.zh.md) 提供异步 flock,无须在用户侧编译。addon 缺失时拒绝写入所有权;Windows 保留其信号量实现。
168
172
 
package/lib/index.js CHANGED
@@ -6,6 +6,7 @@ import { basename, dirname, isAbsolute, join, parse, resolve, toNamespacedPath }
6
6
  import { performance } from "node:perf_hooks";
7
7
  import { scheduler } from "node:timers/promises";
8
8
  import { createHash, randomBytes } from "node:crypto";
9
+ import pLimit from "p-limit";
9
10
  import { SessionAlreadyExistsError, SessionAlreadyOwnedError, SessionFormatUnsupportedError, SessionHandleClosedError, SessionPersistence, SessionPersistenceCorruptionError, SessionPersistenceNotFoundError, SessionPersistenceRevision, SessionReadOnlyError, assertContiguous, assertStoredId, materializeAppendBatch, materializeCreateHeader, sessionFormatVersionRefusal, validateStoredEvents } from "@deepseek-ai/dsh-session-persistence";
10
11
  import { BlockAssembler, errorChain, expandAssistantStream } from "@deepseek-ai/dsh-llm";
11
12
  import { tryLockExclusive } from "@deepseek-ai/node-addon-system/flock";
@@ -401,39 +402,43 @@ var JsonlBackendTracker = class {
401
402
  * sessions' events by id; the teardown effect closes every open handle —
402
403
  * close drains the routed buffer — and aggregates failures. This provider
403
404
  * owns no separate storage connection, so closing handles is the complete
404
- * teardown. Registrations are effects of the current fiber.
405
- * @param ctx - the backend's context.
405
+ * teardown. The returned effect removes listeners before closing handles.
406
+ * @param ctx - the backend's resource-owning context.
407
+ * @returns the disposer to run after persistence consumers finish unloading.
406
408
  */
407
409
  install(ctx) {
408
- ctx.on("session/event", (session, event) => {
409
- this.writers.get(session.id)?.enqueueLive(event, (error) => {
410
- ctx.logger.warn(`session-persistence: background write for session "${session.id}" failed (buffered events retained): ${String(error)}`);
410
+ const { writers, openHandles, name } = this;
411
+ return ctx.effect(function* () {
412
+ yield async () => {
413
+ const errors = [];
414
+ for (const handle of [...openHandles]) try {
415
+ await handle.close();
416
+ } catch (error) {
417
+ errors.push(error);
418
+ }
419
+ if (errors.length > 0) throw new AggregateError(errors, `${name} dispose failed`);
420
+ };
421
+ yield ctx.on("session/event", (session, event) => {
422
+ writers.get(session.id)?.enqueueLive(event, (error) => {
423
+ ctx.logger.warn(`session-persistence: background write for session "${session.id}" failed (buffered events retained): ${String(error)}`);
424
+ });
411
425
  });
412
- });
413
- ctx.on("session/flush", (session) => {
414
- const writer = this.writers.get(session.id);
415
- if (writer === null || writer === void 0) return void 0;
416
- return (async () => {
417
- await writer.drainLive();
418
- await writer.flush();
419
- })();
420
- });
421
- ctx.on("session/disposed", (session) => {
422
- const writer = this.writers.get(session.id);
423
- if (writer === null || writer === void 0) return;
424
- writer.close().catch((error) => {
425
- ctx.logger.warn(`session-persistence: final drain for session "${session.id}" failed: ${String(error)}`);
426
+ yield ctx.on("session/flush", (session) => {
427
+ const writer = writers.get(session.id);
428
+ if (writer === null || writer === void 0) return void 0;
429
+ return (async () => {
430
+ await writer.drainLive();
431
+ await writer.flush();
432
+ })();
426
433
  });
427
- });
428
- ctx.effect(() => async () => {
429
- const errors = [];
430
- for (const handle of [...this.openHandles]) try {
431
- await handle.close();
432
- } catch (error) {
433
- errors.push(error);
434
- }
435
- if (errors.length > 0) throw new AggregateError(errors, `${this.name} dispose failed`);
436
- }, `${this.name} open handles`);
434
+ yield ctx.on("session/disposed", (session) => {
435
+ const writer = writers.get(session.id);
436
+ if (writer === null || writer === void 0) return;
437
+ writer.close().catch((error) => {
438
+ ctx.logger.warn(`session-persistence: final drain for session "${session.id}" failed: ${String(error)}`);
439
+ });
440
+ });
441
+ }, `${this.name} live routing and open handles`);
437
442
  }
438
443
  };
439
444
  //#endregion
@@ -2295,6 +2300,8 @@ function assertZstdHeaderFrame(plaintext) {
2295
2300
  }
2296
2301
  /** Loader schema for the JSONL artifact's physical encoding. */
2297
2302
  const JsonlCompressionSchema = z.union([z.const("zstd"), z.const("none")]).default(DEFAULT_COMPRESSION);
2303
+ /** Default maximum listing filesystem operations in flight per backend. */
2304
+ const DEFAULT_LIST_CONCURRENCY = 3;
2298
2305
  /** Deep-freeze acyclic stored JSON; its arrays contain only indexed JSON values. */
2299
2306
  function freezeStoredEvent(event) {
2300
2307
  const pending = [event];
@@ -2334,6 +2341,30 @@ function fileRevision(identity) {
2334
2341
  function isENOENT(error) {
2335
2342
  return error?.code === "ENOENT";
2336
2343
  }
2344
+ /**
2345
+ * Run `task` over `items` through the backend's shared listing limiter and
2346
+ * settle every call. Callers consume the outcomes in input order, so the first
2347
+ * failure they report matches a sequential loop whatever the completion order.
2348
+ * A limited task must never wait on the same limiter.
2349
+ * @param limit - the backend's shared listing limiter.
2350
+ * @param items - inputs in their sequential order.
2351
+ * @param task - per-item operation.
2352
+ * @returns one outcome per item, in input order.
2353
+ */
2354
+ function settleLimited(limit, items, task) {
2355
+ return Promise.allSettled(items.map((item) => limit(() => task(item))));
2356
+ }
2357
+ /**
2358
+ * Unwrap outcomes from {@link settleLimited}, rethrowing the first rejection in input order.
2359
+ * @param outcomes - outcomes in input order.
2360
+ * @returns the fulfilled values in input order.
2361
+ */
2362
+ function settledValues(outcomes) {
2363
+ return outcomes.map((outcome) => {
2364
+ if (outcome.status === "rejected") throw outcome.reason;
2365
+ return outcome.value;
2366
+ });
2367
+ }
2337
2368
  /** Whether a filesystem-owned failure should retain its original errno and path. */
2338
2369
  function isErrnoException(error) {
2339
2370
  return typeof error?.code === "string";
@@ -2364,23 +2395,25 @@ function waitWithAbort(operation, signal) {
2364
2395
  });
2365
2396
  }
2366
2397
  /**
2367
- * The JSONL persistence backend. Load as a plugin; it registers as
2368
- * `ctx.sessionPersistence`. Sessions materialize lazily: a created session is
2398
+ * The JSONL backend registered as `ctx.sessionPersistence` by the plugin.
2399
+ * Sessions materialize lazily: a created session is
2369
2400
  * visible to this process immediately, reaches disk on its first append or
2370
2401
  * flush, and never existed if the process crashes before that.
2371
2402
  */
2372
2403
  var JsonlSessionPersistence = class extends SessionPersistence {
2373
2404
  config;
2374
- static Config = z.object({
2375
- root: z.string().required(),
2376
- compression: JsonlCompressionSchema
2377
- });
2405
+ tracker;
2378
2406
  /** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
2379
2407
  name = "session-persistence-jsonl";
2380
2408
  root;
2381
2409
  compression;
2410
+ /**
2411
+ * Bounds directory, header, and stat I/O across every concurrent listing of
2412
+ * this backend (`list()`, the root encoding check, historical fingerprints).
2413
+ * Queued tasks of a cancelled listing run and reject at their signal check.
2414
+ */
2415
+ listLimit;
2382
2416
  rootEncodingCheck;
2383
- tracker = new JsonlBackendTracker(this.name);
2384
2417
  generationFormat;
2385
2418
  /**
2386
2419
  * Bounded LRU of parsed, validated stored logs keyed by session id and
@@ -2392,13 +2425,15 @@ var JsonlSessionPersistence = class extends SessionPersistence {
2392
2425
  coldLogMemo = /* @__PURE__ */ new Map();
2393
2426
  /** One joinable decode/migration operation per selected historical Session file revision. */
2394
2427
  migrationPreparations = /* @__PURE__ */ new Map();
2395
- constructor(ctx, config) {
2428
+ constructor(ctx, config, tracker) {
2396
2429
  super(ctx);
2397
2430
  this.config = config;
2431
+ this.tracker = tracker;
2398
2432
  /* v8 ignore next 5 -- generated catalog and Session source share one build-time version owner. */
2399
2433
  if (sessionFormatCatalog.currentVersion !== SESSION_FORMAT_VERSION) throw new Error(`session-persistence-jsonl: format catalog v${sessionFormatCatalog.currentVersion} does not match Session v${SESSION_FORMAT_VERSION}`);
2400
2434
  this.root = resolve(config.root);
2401
2435
  this.compression = config.compression ?? DEFAULT_COMPRESSION;
2436
+ this.listLimit = pLimit(config.listConcurrency ?? DEFAULT_LIST_CONCURRENCY);
2402
2437
  this.generationFormat = {
2403
2438
  currentVersion: sessionFormatCatalog.currentVersion,
2404
2439
  encodeHeader: (header, inheritedEventCount) => sessionFormatCatalog.encodeCurrentHeader(header, inheritedEventCount),
@@ -2406,7 +2441,6 @@ var JsonlSessionPersistence = class extends SessionPersistence {
2406
2441
  isUnsupportedMigrationError: (error) => error instanceof SessionFormatUnsupportedMigrationError
2407
2442
  };
2408
2443
  this.assertUsableRoot();
2409
- this.tracker.install(ctx);
2410
2444
  }
2411
2445
  /**
2412
2446
  * Refusal-diagnostics hook: the absolute target path, without touching the filesystem.
@@ -2573,22 +2607,31 @@ var JsonlSessionPersistence = class extends SessionPersistence {
2573
2607
  const pending = [...this.tracker.pendingEntries()];
2574
2608
  const artifacts = await this.listArtifacts(signal);
2575
2609
  const corpusRevision = artifacts.some((artifact) => artifact.sourceVersion < SESSION_FORMAT_VERSION) ? await this.historicalCorpusRevision(signal) : void 0;
2576
- for (const artifact of artifacts) {
2610
+ const statted = settledValues(await settleLimited(this.listLimit, artifacts, async (artifact) => {
2577
2611
  signal?.throwIfAborted();
2578
2612
  try {
2579
2613
  const identity = await stat(artifact.path, { bigint: true });
2580
2614
  signal?.throwIfAborted();
2581
- listed.add(artifact.header.id);
2582
- snapshots.push({
2583
- header: artifact.header,
2584
- formatStatus: artifact.formatStatus,
2585
- revision: artifact.sourceVersion < SESSION_FORMAT_VERSION ? SessionPersistenceRevision(`${fileRevision(identity)}:${corpusRevision}`) : fileRevision(identity),
2586
- sizeBytes: Number(identity.size)
2587
- });
2615
+ return {
2616
+ artifact,
2617
+ identity
2618
+ };
2588
2619
  } catch (error) {
2589
2620
  signal?.throwIfAborted();
2590
2621
  if (!isENOENT(error)) throw error;
2622
+ return;
2591
2623
  }
2624
+ }));
2625
+ for (const entry of statted) {
2626
+ if (entry === void 0) continue;
2627
+ const { artifact, identity } = entry;
2628
+ listed.add(artifact.header.id);
2629
+ snapshots.push({
2630
+ header: artifact.header,
2631
+ formatStatus: artifact.formatStatus,
2632
+ revision: artifact.sourceVersion < SESSION_FORMAT_VERSION ? SessionPersistenceRevision(`${fileRevision(identity)}:${corpusRevision}`) : fileRevision(identity),
2633
+ sizeBytes: Number(identity.size)
2634
+ });
2592
2635
  }
2593
2636
  for (const [id, entry] of pending) if (!listed.has(id)) snapshots.push({
2594
2637
  header: entry.header,
@@ -3003,29 +3046,56 @@ var JsonlSessionPersistence = class extends SessionPersistence {
3003
3046
  }
3004
3047
  /** Enumerate selected physical generations without interpreting their headers or bodies. */
3005
3048
  async listGenerations(signal) {
3006
- const sources = [];
3007
- for (const project of await this.listProjectDirs(signal)) for (const dir of await this.listSessionDirs(project, signal)) {
3049
+ return (await this.mapSessionDirectories((dir) => {
3008
3050
  signal?.throwIfAborted();
3009
- const selected = await this.resolveGenerationInDirectory(dir, signal);
3010
- if (selected !== void 0) sources.push(selected);
3051
+ return this.resolveGenerationInDirectory(dir, signal);
3052
+ }, signal)).filter((source) => source !== void 0);
3053
+ }
3054
+ /**
3055
+ * Apply `task` to every Session directory through the shared listing
3056
+ * limiter. Results and the first failure follow the sequential
3057
+ * project-then-directory order; a project whose listing fails ends the
3058
+ * traversal after the directories of the projects before it.
3059
+ * @param task - per-directory operation; must not wait on the listing limiter.
3060
+ * @param signal - optional cancellation for directory listings.
3061
+ * @returns per-directory results in traversal order.
3062
+ */
3063
+ async mapSessionDirectories(task, signal) {
3064
+ const limit = this.listLimit;
3065
+ const projects = await settleLimited(limit, await limit(() => this.listProjectDirs(signal)), (project) => this.listSessionDirs(project, signal));
3066
+ const dirs = [];
3067
+ let projectFailure;
3068
+ for (const outcome of projects) {
3069
+ if (outcome.status === "rejected") {
3070
+ projectFailure = outcome;
3071
+ break;
3072
+ }
3073
+ for (const dir of outcome.value) dirs.push(dir);
3011
3074
  }
3012
- return sources;
3075
+ const results = settledValues(await settleLimited(limit, dirs, task));
3076
+ if (projectFailure !== void 0) throw projectFailure.reason;
3077
+ return results;
3013
3078
  }
3014
3079
  /** Historical logical events depend on the corpus, including members with unreadable headers. */
3015
3080
  async historicalCorpusRevision(signal) {
3016
3081
  const paths = (await this.listGenerations(signal)).map((source) => source.sourcePath).sort();
3017
- const hash = createHash("sha256");
3018
- for (const path of paths) {
3082
+ const entries = settledValues(await settleLimited(this.listLimit, paths, async (path) => {
3019
3083
  signal?.throwIfAborted();
3020
- let revision;
3021
3084
  try {
3022
- revision = fileRevision(await stat(path, { bigint: true }));
3085
+ return {
3086
+ path,
3087
+ revision: fileRevision(await stat(path, { bigint: true }))
3088
+ };
3023
3089
  } catch (error) {
3024
3090
  if (!isENOENT(error)) throw error;
3025
- revision = "missing";
3091
+ return {
3092
+ path,
3093
+ revision: "missing"
3094
+ };
3026
3095
  }
3027
- hash.update(JSON.stringify([path, revision]));
3028
- }
3096
+ }));
3097
+ const hash = createHash("sha256");
3098
+ for (const { path, revision } of entries) hash.update(JSON.stringify([path, revision]));
3029
3099
  signal?.throwIfAborted();
3030
3100
  return hash.digest("hex");
3031
3101
  }
@@ -3033,17 +3103,27 @@ var JsonlSessionPersistence = class extends SessionPersistence {
3033
3103
  signal?.throwIfAborted();
3034
3104
  await this.ensureRootEncoding();
3035
3105
  signal?.throwIfAborted();
3036
- const artifacts = [];
3037
- const ids = /* @__PURE__ */ new Set();
3038
- for (const selected of await this.listGenerations(signal)) {
3106
+ const generations = await this.listGenerations(signal);
3107
+ const headers = await settleLimited(this.listLimit, generations, async (selected) => {
3039
3108
  signal?.throwIfAborted();
3040
- let metadata;
3041
3109
  try {
3042
- metadata = await this.readGenerationHeader(selected, void 0, signal);
3110
+ return {
3111
+ selected,
3112
+ metadata: await this.readGenerationHeader(selected, void 0, signal)
3113
+ };
3043
3114
  } catch (error) {
3044
- if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) continue;
3115
+ if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) return {
3116
+ selected,
3117
+ metadata: void 0
3118
+ };
3045
3119
  throw error;
3046
3120
  }
3121
+ });
3122
+ const artifacts = [];
3123
+ const ids = /* @__PURE__ */ new Set();
3124
+ for (const outcome of headers) {
3125
+ if (outcome.status === "rejected") throw outcome.reason;
3126
+ const { selected, metadata } = outcome.value;
3047
3127
  if (metadata === void 0) continue;
3048
3128
  if (ids.has(metadata.header.id)) throw new Error(`duplicate JSONL session id "${metadata.header.id}" appears in multiple project directories`);
3049
3129
  ids.add(metadata.header.id);
@@ -3449,10 +3529,10 @@ var JsonlSessionPersistence = class extends SessionPersistence {
3449
3529
  return this.rootEncodingCheck;
3450
3530
  }
3451
3531
  async checkRootEncoding() {
3452
- for (const project of await this.listProjectDirs()) for (const dir of await this.listSessionDirs(project)) {
3532
+ await this.mapSessionDirectories(async (dir) => {
3453
3533
  const incompatible = await this.findOppositeGenerationInDirectory(dir);
3454
3534
  if (incompatible !== void 0) throw this.encodingMismatch(incompatible);
3455
- }
3535
+ });
3456
3536
  }
3457
3537
  async rejectLegacyFlatArtifact(project, id, signal) {
3458
3538
  signal?.throwIfAborted();
@@ -3527,5 +3607,36 @@ var JsonlSessionPersistence = class extends SessionPersistence {
3527
3607
  }
3528
3608
  }
3529
3609
  };
3610
+ /** JSONL persistence plugin label. */
3611
+ const name = "session-persistence-jsonl";
3612
+ /** Loader schema for the backend's root, physical encoding, and listing concurrency. */
3613
+ const Config = z.object({
3614
+ root: z.string().required(),
3615
+ compression: JsonlCompressionSchema,
3616
+ listConcurrency: z.natural().min(1).default(DEFAULT_LIST_CONCURRENCY)
3617
+ });
3618
+ /**
3619
+ * Mount persistence with live routing and handles retained through the
3620
+ * consumer unloads triggered by removing this provider. Consumers must own
3621
+ * cleanup in their injecting scope; concurrent root disposal is not ordered.
3622
+ * @param ctx - the owning plugin context.
3623
+ * @param config - the storage root, physical encoding, and listing concurrency.
3624
+ * @returns resolves when the service is ready.
3625
+ */
3626
+ async function apply(ctx, config) {
3627
+ let service;
3628
+ ctx.effect(function* () {
3629
+ const tracker = new JsonlBackendTracker(name);
3630
+ yield tracker.install(ctx);
3631
+ service = ctx.plugin({
3632
+ name: "session-persistence-jsonl-service",
3633
+ apply(serviceCtx) {
3634
+ new JsonlSessionPersistence(serviceCtx, config, tracker);
3635
+ }
3636
+ });
3637
+ yield service.dispose;
3638
+ }, "session-persistence-jsonl resources");
3639
+ await service.await();
3640
+ }
3530
3641
  //#endregion
3531
- export { JsonlCompressionSchema, JsonlSessionPersistence as default };
3642
+ export { Config, JsonlCompressionSchema, apply, name };
@@ -7,15 +7,11 @@
7
7
  */
8
8
  import { Context } from '@deepseek-ai/cordis';
9
9
  import z from '@deepseek-ai/schemastery';
10
- import { SessionPersistence, type SessionAccess, type SessionHandle, type SessionHandleReadResult, type SessionPersistenceCreateOptions, type SessionPersistenceListOptions, type SessionPersistenceOpenOptions, type SessionPersistenceSnapshot, type SessionPersistenceStatOptions, type SessionPersistenceRevision as PersistenceRevision } from '@deepseek-ai/dsh-session-persistence';
11
- import { JsonlSessionHandle } from './storage.ts';
12
- import { SessionWriteLease } from './lease.ts';
13
- import type { SessionEvent, SessionId, SessionHeader, SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session';
14
10
  import { type JsonlCompression } from './format.ts';
15
11
  export type { JsonlCompression } from './format.ts';
16
12
  /** Loader schema for the JSONL artifact's physical encoding. */
17
13
  export declare const JsonlCompressionSchema: z<JsonlCompression>;
18
- /** Plugin config for the JSONL backend's root and physical encoding. */
14
+ /** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
19
15
  export interface Config {
20
16
  /**
21
17
  * Root directory for all session files. Required (no default): a default of
@@ -27,253 +23,24 @@ export interface Config {
27
23
  root: string;
28
24
  /** Physical encoding; defaults to checksummed Zstandard frames. */
29
25
  compression?: JsonlCompression;
30
- }
31
- /** One stored event graph whose producer has established immutable sharing. */
32
- interface FrozenStoredEvents extends SessionHandleReadResult {
33
- readonly eventState: 'shared-frozen';
34
- }
35
- /** State shared by prepared historical and published current logs. */
36
- interface StoredLogBase extends FrozenStoredEvents {
37
- readonly meta: SessionHeader;
38
- readonly tornTruncateTo: number | undefined;
39
- /** Complete events recovered from the torn final frame; the write path rewrites them durably. */
40
- readonly recoveredTail: SessionEvent[];
41
- /** Exact fork-inherited prefix length stored in the header line. */
42
- readonly inheritedEventCount: SessionLogOffsetType;
43
- readonly revision: PersistenceRevision;
44
- }
45
- /** A decoded current generation that is already durable. */
46
- interface CurrentStoredLog extends StoredLogBase {
47
- readonly status: 'current';
48
- }
49
- /**
50
- * The JSONL persistence backend. Load as a plugin; it registers as
51
- * `ctx.sessionPersistence`. Sessions materialize lazily: a created session is
52
- * visible to this process immediately, reaches disk on its first append or
53
- * flush, and never existed if the process crashes before that.
54
- */
55
- declare class JsonlSessionPersistence extends SessionPersistence {
56
- config: Config;
57
- static Config: z<Config>;
58
- /** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
59
- readonly name = "session-persistence-jsonl";
60
- private root;
61
- private compression;
62
- private rootEncodingCheck;
63
- private readonly tracker;
64
- private readonly generationFormat;
65
- /**
66
- * Bounded LRU of parsed, validated stored logs keyed by session id and
67
- * guarded by the stat-derived revision, so an immediate cold-read handoff
68
- * (observation then resume) parses the artifact once. Every local mutation
69
- * for an id invalidates its entry; a foreign write misses through the
70
- * revision guard.
71
- */
72
- private readonly coldLogMemo;
73
- /** One joinable decode/migration operation per selected historical Session file revision. */
74
- private readonly migrationPreparations;
75
- constructor(ctx: Context, config: Config);
76
- /**
77
- * Refusal-diagnostics hook: the absolute target path, without touching the filesystem.
78
- * @param meta - the stored header naming the session and its cwd.
79
- * @returns the artifact kind and absolute path.
80
- */
81
- private locate;
82
- /**
83
- * Create a new stored session and take its write ownership. The session is
84
- * visible to this process immediately; the physical artifact appears on the
85
- * first append or flush.
86
- * @param header - the immutable header to store; must be losslessly
87
- * JSON-serializable with a non-negative safe-integer `createdAt`.
88
- * @param options - optional cancellation.
89
- * @returns the owned write handle.
90
- */
91
- create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle>;
92
- /**
93
- * Open an existing stored session for `read` or single-writer `write`.
94
- * @param id - the stored session to open.
95
- * @param access - `read` (no ownership) or `write` (atomic in-process claim).
96
- * @param options - optional cancellation.
97
- * @returns the open handle.
98
- */
99
- open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle>;
100
- /**
101
- * Flush every active write handle in one durability barrier; see the seam
102
- * contract.
103
- * @returns resolution once every write handle active at the call has flushed.
104
- */
105
- flush(): Promise<void>;
106
- /**
107
- * Observe one stored session without reading its event log.
108
- * @param id - the stored session to observe.
109
- * @param options - optional cancellation.
110
- * @returns the snapshot (`sizeBytes` carries the physical artifact size), or
111
- * `undefined` when the session does not exist.
112
- */
113
- stat(id: SessionId, options?: SessionPersistenceStatOptions): Promise<SessionPersistenceSnapshot | undefined>;
114
- /**
115
- * List every stored session visible to this process: materialized artifacts
116
- * plus this process's created-but-unmaterialized sessions.
117
- * @param options - optional cancellation.
118
- * @returns one snapshot per session, in no promised order.
119
- */
120
- list(options?: SessionPersistenceListOptions): Promise<readonly SessionPersistenceSnapshot[]>;
121
- /** Resolve and read one stored log, refusing loudly when the artifact is absent. */
122
- private requireStoredLog;
123
- /** Probe the memo and otherwise decode one historical generation under backend cancellation. */
124
- private loadStoredMigration;
125
- /** Await shared preparation for one caller and abort it only after its last waiter leaves. */
126
- private waitForPreparation;
127
- /** Decode one historical generation without publishing a successor. */
128
- private prepareStoredMigration;
129
- /** Publish a prepared historical log before granting write access. */
130
- private publishStoredMigration;
131
- /** Translate generation-layer failures into the persistence seam's error vocabulary. */
132
- private generationFailure;
133
- /**
134
- * Read, parse, and validate one stored log as the current logical prefix.
135
- * @param path - the artifact file to read.
136
- * @param expectedId - the session identity the artifact must carry.
137
- * @param signal - optional cancellation for the stat/read/decode work.
138
- * @returns the validated stored log with any torn-tail truncation point.
139
- */
140
- readStoredLog(path: string, expectedId: SessionId, signal?: AbortSignal): Promise<CurrentStoredLog>;
141
- /** Decode and memoize one already-stable current physical snapshot. */
142
- private decodeStoredLog;
143
- /** Insert one parsed log into the bounded handoff cache. */
144
- private memoizeStoredLog;
145
- /**
146
- * Resolve a session's current-generation log path.
147
- * @param id - the stored session to locate.
148
- * @param signal - optional cancellation for the directory scans.
149
- * @returns the current artifact path, or `undefined` while only a historical generation exists.
150
- */
151
- resolveCurrentLog(id: SessionId, signal?: AbortSignal): Promise<string | undefined>;
152
- /**
153
- * Durably append one validated batch; lazily materializes on the first write.
154
- * @param header - the session's stored header.
155
- * @param events - the validated contiguous batch, in seq order.
156
- * @param isMaterialized - whether the session already has a durable artifact.
157
- * @param inheritedEventCount - the exact fork-inherited prefix length written into a materializing header line.
158
- */
159
- persistBatch(header: SessionHeader, events: readonly SessionEvent[], isMaterialized: boolean, inheritedEventCount: SessionLogOffsetType): Promise<void>;
160
- /**
161
- * Materialize a header-only artifact for an explicitly durable empty session.
162
- * @param header - the session's stored header.
163
- * @param inheritedEventCount - the exact fork-inherited prefix length written into the header line.
164
- */
165
- persistHeader(header: SessionHeader, inheritedEventCount: SessionLogOffsetType): Promise<void>;
166
- /**
167
- * Truncate a torn physical tail durably before this session's first new append.
168
- * @param header - the session's stored header.
169
- * @param truncateTo - the byte offset the artifact is truncated to.
170
- */
171
- truncateTornTail(header: SessionHeader, truncateTo: number): Promise<void>;
172
- /**
173
- * Whether this process still tracks a created-but-unmaterialized session.
174
- * @param id - the session to test.
175
- * @returns true while the pending entry exists.
176
- */
177
- hasPendingSession(id: SessionId): boolean;
178
- /**
179
- * Release one handle's backend bookkeeping on close.
180
- * @param handle - the closing handle.
181
- * @param materialized - whether the session reached durable storage.
182
- */
183
- releaseHandle(handle: JsonlSessionHandle, materialized: boolean): void;
184
- /**
185
- * Acquire the session directory's kernel write lock; the kernel holds it
186
- * until the handle's close releases the descriptor, including on process death.
187
- * @param id - the session the lock guards.
188
- * @param cwd - header cwd used to derive the directory for a fresh session.
189
- * @param dir - the resolved directory of an existing artifact, when known.
190
- * @returns the held lock.
191
- */
192
- private acquireLease;
193
- /**
194
- * Acquire the cross-process write lock for a materializing created session,
195
- * called by its handle immediately before the first log bytes publish.
196
- * @param header - the session's stored header (its cwd derives the directory).
197
- * @returns the held lock.
198
- */
199
- acquireWriteLease(header: SessionHeader): Promise<SessionWriteLease>;
200
- /** Decode complete frames and retain complete JSONL records from a torn final frame. */
201
- private readZstdPrefix;
202
- /** Enumerate selected physical generations without interpreting their headers or bodies. */
203
- private listGenerations;
204
- /** Historical logical events depend on the corpus, including members with unreadable headers. */
205
- private historicalCorpusRevision;
206
- private listArtifacts;
207
- /** Read and translate one selected generation header without inspecting its body. */
208
- private readGenerationHeader;
209
- /** Convert format-catalog string identities to current branded Session metadata. */
210
- private currentHeader;
211
- /** Atomically write the header line + first batch (temp-write, fsync, publish). */
212
- private materialize;
213
- private materializePosix;
214
- private materializeWin32;
215
- private rejectExistingLog;
216
- private writeSyncedTempFile;
217
- /** Encode the header and first batch without combining their frame boundaries. */
218
- private encodeMaterialization;
219
- /** Encode one durable append batch in the configured physical representation. */
220
- private encodeEventBatch;
221
- /** fsync a POSIX directory so a just-created/renamed entry is crash-durable. */
222
- private syncDirPosix;
223
- /**
224
- * Append and fsync event lines. On a partial write or sync failure, restore the
225
- * previous size before rethrowing because the unchanged cursor will retry the
226
- * batch; leaving partial bytes would create duplicate sequence numbers.
227
- */
228
- private appendLines;
229
- private rollbackAppend;
230
- /** Truncate the log file to `offset` bytes and fsync (discard the crash tail). */
231
- private repair;
232
- /**
233
- * Read the first newline-terminated line of a file without loading the whole
234
- * file. Returns undefined if the file is empty or has no complete first line.
235
- * Reads in bounded chunks so a huge log costs only the header read.
236
- */
237
- private readFirstLine;
238
- /** Read only the header frame; compression failures reject as corruption, while I/O and cancellation propagate. */
239
- private readFirstZstdLine;
240
- /** Select the numerically highest canonical generation in one Session directory. */
241
- private resolveGenerationInDirectory;
242
- /** Find the unique authoritative generation for an id across project directories. */
243
- private findLog;
244
- /** Require an existing configured root to be a readable directory. */
245
- private assertUsableRoot;
246
- /** Reject metadata that does not identify the selected physical log. */
247
- private assertStoredIdentity;
248
- /** Validate a supported historical header against the selected source path. */
249
- private validateSourceIdentity;
250
26
  /**
251
- * Whether two path spellings resolve to the same physical file. This admits
252
- * case aliases on case-insensitive filesystems without weakening identity
253
- * checks on case-sensitive stores.
27
+ * Maximum directory, header, and stat reads in flight across all concurrent
28
+ * listings of this backend (`list()`, the root encoding check, and historical
29
+ * fingerprints). Defaults to 3.
254
30
  */
255
- private sameFile;
256
- /** The human-readable project directories under the configured root. */
257
- private listProjectDirs;
258
- /** List session-owned directories and reject the obsolete flat-file layout. */
259
- private listSessionDirs;
260
- /** Reject a root that already belongs to the other physical encoding. */
261
- private ensureRootEncoding;
262
- private checkRootEncoding;
263
- private rejectLegacyFlatArtifact;
264
- private rejectOppositeArtifact;
265
- /** Return the highest canonical generation encoded with the other configured suffix. */
266
- private findOppositeGenerationInDirectory;
267
- private oppositeCompression;
268
- private encodingMismatch;
269
- private legacyLayout;
270
- private exists;
271
- private assertLogParentAllowsAbsence;
31
+ listConcurrency?: number;
272
32
  }
33
+ /** JSONL persistence plugin label. */
34
+ export declare const name = "session-persistence-jsonl";
35
+ /** Loader schema for the backend's root, physical encoding, and listing concurrency. */
36
+ export declare const Config: z<Config>;
273
37
  /**
274
- * One open channel onto a JSONL-stored session: the shared storage-handle
275
- * scaffolding over this backend's file primitives. Reads re-scan the artifact
276
- * under the stable-read loop.
38
+ * Mount persistence with live routing and handles retained through the
39
+ * consumer unloads triggered by removing this provider. Consumers must own
40
+ * cleanup in their injecting scope; concurrent root disposal is not ordered.
41
+ * @param ctx - the owning plugin context.
42
+ * @param config - the storage root, physical encoding, and listing concurrency.
43
+ * @returns resolves when the service is ready.
277
44
  */
278
- export default JsonlSessionPersistence;
45
+ export declare function apply(ctx: Context, config: Config): Promise<void>;
279
46
  //# sourceMappingURL=index.d.ts.map
@@ -241,9 +241,10 @@ export declare class JsonlBackendTracker {
241
241
  * sessions' events by id; the teardown effect closes every open handle —
242
242
  * close drains the routed buffer — and aggregates failures. This provider
243
243
  * owns no separate storage connection, so closing handles is the complete
244
- * teardown. Registrations are effects of the current fiber.
245
- * @param ctx - the backend's context.
244
+ * teardown. The returned effect removes listeners before closing handles.
245
+ * @param ctx - the backend's resource-owning context.
246
+ * @returns the disposer to run after persistence consumers finish unloading.
246
247
  */
247
- install(ctx: Context): void;
248
+ install(ctx: Context): () => Promise<void>;
248
249
  }
249
250
  //# sourceMappingURL=storage.d.ts.map
package/lib/worker.cjs CHANGED
@@ -3148,6 +3148,8 @@ const KNOWN_SESSION_EVENT_TYPES = new Set([
3148
3148
  "hook/invoked",
3149
3149
  "hook/result",
3150
3150
  "image/offload",
3151
+ "job/registered",
3152
+ "job/settled",
3151
3153
  "llm/retry",
3152
3154
  "llm/retry-started",
3153
3155
  "model/selection",
@@ -3621,7 +3623,7 @@ const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-method
3621
3623
  * a Host composition to read it.
3622
3624
  * @param service - owning Service instance, normally `this`.
3623
3625
  * @param serviceKey - exact Cordis service key.
3624
- * @param options - optional distinct wire namespace.
3626
+ * @param options - optional wire namespace.
3625
3627
  * @returns a frozen, inspectable binding with no compiler-injected metadata.
3626
3628
  */
3627
3629
  function bindTypertRemote(service, serviceKey, options = {}) {
@@ -3629,7 +3631,7 @@ function bindTypertRemote(service, serviceKey, options = {}) {
3629
3631
  const namespace = options.namespace ?? serviceKey;
3630
3632
  validateName("namespace", namespace);
3631
3633
  const ctx = Reflect.get(service, "ctx");
3632
- if (ctx instanceof Context) provideInvocationAccessor(ctx);
3634
+ if (Context.is(ctx)) provideInvocationAccessor(ctx);
3633
3635
  return Object.freeze({
3634
3636
  service,
3635
3637
  serviceKey,
@@ -3644,7 +3646,7 @@ var TypertRemoteService = class extends Service {
3644
3646
  * Register the Service and bind the same key to Typert Gateway.
3645
3647
  * @param ctx - owning Cordis Context.
3646
3648
  * @param serviceKey - exact Cordis service key and default wire namespace.
3647
- * @param options - optional distinct wire namespace.
3649
+ * @param options - optional wire namespace.
3648
3650
  */
3649
3651
  constructor(ctx, serviceKey, options = {}) {
3650
3652
  super(ctx, serviceKey);
@@ -3664,21 +3666,42 @@ function provideInvocationAccessor(ctx) {
3664
3666
  function Remote(methodExportOrOptions, context) {
3665
3667
  if (typeof methodExportOrOptions === "string") {
3666
3668
  validateName("Remote export name", methodExportOrOptions);
3667
- return remoteDecorator({ kind: "direct" }, void 0, methodExportOrOptions);
3668
- }
3669
- if (typeof methodExportOrOptions === "object") {
3670
- if (remoteOptionMode(methodExportOrOptions) !== "stream" || Reflect.ownKeys(methodExportOrOptions).length !== 1) throw new TypeError("typert-protocol: Remote options must contain exactly mode: \"stream\"");
3671
- return remoteDecorator({ kind: "direct" }, "stream");
3669
+ return remoteDecorator({ kind: "direct" }, { exportName: methodExportOrOptions });
3672
3670
  }
3671
+ if (typeof methodExportOrOptions === "object") return remoteDecorator({ kind: "direct" }, markerOptions(methodExportOrOptions, REMOTE_OPTION_KEYS, "Remote options require name, mode: \"stream\", or resources"));
3673
3672
  if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
3674
3673
  addMarkerInitializer(context, { kind: "direct" });
3675
3674
  }
3676
- function remoteOptionMode(options) {
3677
- return Reflect.get(options, "mode");
3675
+ const REMOTE_OPTION_KEYS = new Set([
3676
+ "name",
3677
+ "mode",
3678
+ "resources"
3679
+ ]);
3680
+ /** Validate one decorator options object against its accepted keys and select the marker fields. */
3681
+ function markerOptions(options, accepted, requirement) {
3682
+ const keys = Reflect.ownKeys(options);
3683
+ if (keys.length === 0 || keys.some((key) => typeof key !== "string" || !accepted.has(key)) || Object.hasOwn(options, "mode") && options.mode !== "stream") throw new TypeError(`typert-protocol: ${requirement}`);
3684
+ const { mode, name, resources } = options;
3685
+ if (name !== void 0) validateName("Remote export name", name);
3686
+ return {
3687
+ ...mode === void 0 ? {} : { mode },
3688
+ ...name === void 0 ? {} : { exportName: name },
3689
+ ...resources === void 0 ? {} : { resources: resourceReaders(resources) }
3690
+ };
3691
+ }
3692
+ /** Freeze declared readers into the marker record; a misdeclared reader fails at decoration. */
3693
+ function resourceReaders(resources) {
3694
+ const readers = {};
3695
+ for (const [kind, reader] of Object.entries(resources)) {
3696
+ if (typeof reader !== "function") throw new TypeError(`typert-protocol: Remote resource reader "${kind}" must be a function`);
3697
+ readers[kind] = reader;
3698
+ }
3699
+ if (Object.keys(readers).length === 0) throw new TypeError("typert-protocol: Remote resources require at least one reader");
3700
+ return Object.freeze(readers);
3678
3701
  }
3679
- function remoteDecorator(invocation, mode, exportName) {
3702
+ function remoteDecorator(invocation, options = {}) {
3680
3703
  return function(_method, context) {
3681
- addMarkerInitializer(context, invocation, mode, exportName);
3704
+ addMarkerInitializer(context, invocation, options);
3682
3705
  };
3683
3706
  }
3684
3707
  function readRemoteMethodDescriptor(prototype) {
@@ -3692,26 +3715,27 @@ function readRemoteMethodDescriptor(prototype) {
3692
3715
  if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
3693
3716
  return descriptor;
3694
3717
  }
3695
- function addMarkerInitializer(context, invocation, mode, exportName) {
3718
+ function addMarkerInitializer(context, invocation, options = {}) {
3696
3719
  if (context.private || context.static || typeof context.name !== "string") throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");
3697
3720
  const method = context.name;
3698
3721
  context.addInitializer(function() {
3699
3722
  const prototype = Object.getPrototypeOf(this);
3700
3723
  if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
3701
- mark(prototype, method, invocation, mode, exportName);
3724
+ mark(prototype, method, invocation, options);
3702
3725
  });
3703
3726
  }
3704
- function mark(prototype, method, invocation, mode, exportName) {
3727
+ function mark(prototype, method, invocation, { mode, exportName, resources }) {
3705
3728
  const descriptor = readRemoteMethodDescriptor(prototype);
3706
3729
  const marker = Object.freeze({
3707
3730
  method,
3708
3731
  ...exportName === void 0 || exportName === method ? {} : { exportName },
3709
3732
  ...mode === void 0 ? {} : { mode },
3710
- invocation: Object.freeze(invocation)
3733
+ invocation: Object.freeze(invocation),
3734
+ ...resources === void 0 ? {} : { resources }
3711
3735
  });
3712
3736
  const current = descriptor?.methods.find((candidate) => candidate.method === method);
3713
3737
  if (current !== void 0) {
3714
- if (current.exportName === marker.exportName && current.mode === marker.mode && sameInvocation(current.invocation, invocation)) return;
3738
+ if (current.exportName === marker.exportName && current.mode === marker.mode && current.resources === marker.resources && sameInvocation(current.invocation, invocation)) return;
3715
3739
  throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
3716
3740
  }
3717
3741
  Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
@@ -5556,10 +5580,7 @@ var LlmError = class extends HarnessError {
5556
5580
  if (entry.provider.length === 0 || entry.displayName.length === 0 || entry.settingsNs.length === 0) throw new LlmError("configurable providers need a non-empty provider, displayName, and settingsNs", "INVALID_DIRECTORY");
5557
5581
  if (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider "${entry.provider}" has an empty settingsPath segment`, "INVALID_DIRECTORY");
5558
5582
  if (this.directory.has(entry.provider) && !own.has(entry.provider) || detached.some((seen) => seen.provider === entry.provider)) throw new LlmError(`configurable provider "${entry.provider}" is already declared`, "DUPLICATE_DIRECTORY");
5559
- detached.push({
5560
- ...entry,
5561
- settingsPath: [...entry.settingsPath]
5562
- });
5583
+ detached.push(detachDirectoryEntry(entry));
5563
5584
  }
5564
5585
  for (const entry of held) this.directory.delete(entry.provider);
5565
5586
  for (const entry of detached) this.directory.set(entry.provider, entry);
@@ -5588,10 +5609,7 @@ var LlmError = class extends HarnessError {
5588
5609
  * @returns detached directory entries in declaration order.
5589
5610
  */
5590
5611
  listConfigurableProviders() {
5591
- return [...this.directory.values()].map((entry) => ({
5592
- ...entry,
5593
- settingsPath: [...entry.settingsPath]
5594
- }));
5612
+ return [...this.directory.values()].map(detachDirectoryEntry);
5595
5613
  }
5596
5614
  /**
5597
5615
  * Offer to interrogate provider endpoints on behalf of the settings
@@ -5683,6 +5701,16 @@ var LlmError = class extends HarnessError {
5683
5701
  return this.adapters.get(provider)?.adapter.imageRequestPricing(provider, model);
5684
5702
  }
5685
5703
  /**
5704
+ * Resolve the image projection for an exact registered model route.
5705
+ * @param provider - registered provider route.
5706
+ * @param model - exact model id.
5707
+ * @param image - normalized image reference.
5708
+ * @returns dimensions and byte target used by the adapter's request serializer.
5709
+ */
5710
+ imageRequestTarget(provider, model, image) {
5711
+ return this.registration(provider).adapter.imageRequestTarget(provider, model, image);
5712
+ }
5713
+ /**
5686
5714
  * Resolve the exact text one durable file occurrence contributes to every
5687
5715
  * provider request in the current execution environment.
5688
5716
  * @param ref - durable verbatim file reference from model history.
@@ -6031,6 +6059,19 @@ function adapterFailureChunk(error, signal) {
6031
6059
  }
6032
6060
  };
6033
6061
  }
6062
+ /** Copy a directory entry, including its arrays, so neither side can mutate the other's copy. */
6063
+ function detachDirectoryEntry(entry) {
6064
+ const { nativeAuth } = entry;
6065
+ return {
6066
+ ...entry,
6067
+ settingsPath: [...entry.settingsPath],
6068
+ ...entry.baseURLEnv === void 0 ? {} : { baseURLEnv: [...entry.baseURLEnv] },
6069
+ ...nativeAuth === void 0 ? {} : { nativeAuth: {
6070
+ ...nativeAuth,
6071
+ env: [...nativeAuth.env]
6072
+ } }
6073
+ };
6074
+ }
6034
6075
  //#endregion
6035
6076
  //#region ../../core/session/src/request-header.ts
6036
6077
  /**
package/locale/en.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "meta": {
3
+ "title": "session-persistence-jsonl"
4
+ }
5
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "会话日志持久保存",
4
+ "description": "将会话日志保存为本地 JSONL 文件,供后续恢复和读取。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-session-persistence-jsonl",
3
3
  "description": "JSONL durable session persistence backend for the DeepSeek Harness",
4
- "version": "0.2.1-alpha.2",
4
+ "version": "0.2.1-alpha.3",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -19,32 +19,35 @@
19
19
  "default": "./lib/index.js"
20
20
  },
21
21
  "./src/*": "./src/*",
22
- "./package.json": "./package.json"
22
+ "./package.json": "./package.json",
23
+ "./locale/*.json": "./locale/*.json"
23
24
  },
24
25
  "files": [
26
+ "locale/*.json",
25
27
  "lib/index.js",
26
28
  "lib/worker.cjs",
27
29
  "lib/types/**/*.d.ts"
28
30
  ],
29
31
  "license": "MIT",
30
32
  "peerDependencies": {
31
- "@deepseek-ai/dsh-session": "0.2.1-alpha.2",
32
- "@deepseek-ai/dsh-session-persistence": "0.2.1-alpha.2",
33
- "@deepseek-ai/cordis": "~4.0.5-alpha.1"
33
+ "@deepseek-ai/dsh-session": "0.2.1-alpha.3",
34
+ "@deepseek-ai/dsh-session-persistence": "0.2.1-alpha.3",
35
+ "@deepseek-ai/cordis": "~4.0.5-alpha.2"
34
36
  },
35
37
  "dependencies": {
36
- "@deepseek-ai/dsh-llm": "0.2.1-alpha.2",
37
- "@deepseek-ai/dsh-session-format": "0.2.1-alpha.2",
38
- "@deepseek-ai/dsh-session-format-catalog": "0.2.1-alpha.2",
39
- "@deepseek-ai/dsh-session-format-v3-to-v4": "0.2.1-alpha.2",
38
+ "@deepseek-ai/dsh-llm": "0.2.1-alpha.3",
39
+ "@deepseek-ai/dsh-session-format": "0.2.1-alpha.3",
40
+ "@deepseek-ai/dsh-session-format-catalog": "0.2.1-alpha.3",
41
+ "@deepseek-ai/dsh-session-format-v3-to-v4": "0.2.1-alpha.3",
40
42
  "@deepseek-ai/node-addon-system": "~0.1.2",
41
- "@deepseek-ai/schemastery": "~3.18.5-alpha.1",
42
- "koffi": "3.1.1"
43
+ "@deepseek-ai/schemastery": "~3.18.5-alpha.2",
44
+ "koffi": "3.1.1",
45
+ "p-limit": "7.3.3"
43
46
  },
44
47
  "devDependencies": {
45
- "@deepseek-ai/dsh-session": "0.2.1-alpha.2",
46
- "@deepseek-ai/dsh-session-format-v0-to-v1": "0.2.1-alpha.2",
47
- "@deepseek-ai/dsh-session-persistence": "0.2.1-alpha.2",
48
- "@deepseek-ai/cordis": "~4.0.5-alpha.1"
48
+ "@deepseek-ai/dsh-session": "0.2.1-alpha.3",
49
+ "@deepseek-ai/dsh-session-format-v0-to-v1": "0.2.1-alpha.3",
50
+ "@deepseek-ai/dsh-session-persistence": "0.2.1-alpha.3",
51
+ "@deepseek-ai/cordis": "~4.0.5-alpha.2"
49
52
  }
50
53
  }