@x-otto/session 0.0.1-alpha.0 → 0.0.1-alpha.2
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.md +12 -17
- package/dist/index.d.ts +108 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -9
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -34,13 +34,15 @@ Message history as an entry tree:
|
|
|
34
34
|
|
|
35
35
|
- `SessionEntry<T>` discriminated union: `message` / `compaction` / `clear`
|
|
36
36
|
- `walkBranch()` — traverse along `parentId` chain to `leafId`
|
|
37
|
-
- `recordCompaction(summary, replacement)` — adds a compaction entry with incremental replacement stripping of the prior boundary
|
|
37
|
+
- `recordCompaction(summary, replacement)` — adds a compaction entry with incremental replacement stripping of the prior boundary
|
|
38
38
|
- `branch(entryId)` — fork by resetting `leafId`; fail-fast if target boundary is stripped
|
|
39
39
|
- `buildContext()` — walks from the most recent boundary (compaction/clear), consuming only its `replacement`
|
|
40
40
|
- `capStoredHistory(max)` — pure in-memory limit (DB retains all data, append-forever)
|
|
41
|
-
- `capStoredHistoryByBytes(maxBytes)` —
|
|
41
|
+
- `capStoredHistoryByBytes(maxBytes)` — a hard byte-budget gate
|
|
42
42
|
|
|
43
|
-
### Data Safety Invariants
|
|
43
|
+
### Data Safety Invariants
|
|
44
|
+
|
|
45
|
+
Following a real production data-loss incident, these invariants are enforced:
|
|
44
46
|
|
|
45
47
|
| Invariant | Guard |
|
|
46
48
|
|-----------|-------|
|
|
@@ -50,13 +52,13 @@ Message history as an entry tree:
|
|
|
50
52
|
| Stripped state NEVER persisted/checkpointed/forked | `appendEntry` first-line reject + runtime 4-exit assertions + `branch()` fail-fast |
|
|
51
53
|
| Blob absence = fail-fast on assembly | `decodeReplacementFromBlobs` throws on missing blob |
|
|
52
54
|
|
|
53
|
-
### Relational Persistence
|
|
55
|
+
### Relational Persistence
|
|
54
56
|
|
|
55
57
|
`SqliteSessionRepository` (`SESSION_MIGRATIONS` v1-v5) + `RelationalSessionPersistence` — the production persistence path:
|
|
56
58
|
|
|
57
59
|
**Write**: incremental append via `entry_id` cursor (fallback to full idempotent append with `ON CONFLICT(session_id, entry_id) DO NOTHING`). Compaction replacement encoded to content-addressed blobs (sha256 → `message_blobs` dedup) before append.
|
|
58
60
|
|
|
59
|
-
**Read**: tail window (load last N entries when DB exceeds `maxLoadEntries`), inactive replacement stripping (only active boundary retains replacement; new-format rows mark with zero blob reads), dual-format assembly (old inline / new hashes,
|
|
61
|
+
**Read**: tail window (load last N entries when DB exceeds `maxLoadEntries`), inactive replacement stripping (only active boundary retains replacement; new-format rows mark with zero blob reads), dual-format assembly (old inline / new hashes, assembly-equivalent).
|
|
60
62
|
|
|
61
63
|
**Hydrate**: `loadEntriesByIds` point query + `hydrateStrippedReplacements` (dual-format). `ReplacementHydrationCapable` capability interface for runtime 4-exit detection (checkpoint, forkSession, forkFromCheckpoint, restore).
|
|
62
64
|
|
|
@@ -77,7 +79,7 @@ src/
|
|
|
77
79
|
session-repository.ts # SessionRepository interface
|
|
78
80
|
sqlite-session-repository.ts # SQLite + MIGRATIONS v1-v5 (message_blobs)
|
|
79
81
|
relational-session-persistence.ts # Incremental append + lease gate + tail window + hydration
|
|
80
|
-
relational-bridge.ts # Snapshot↔rows bridge + dual-format assembly
|
|
82
|
+
relational-bridge.ts # Snapshot↔rows bridge + dual-format assembly
|
|
81
83
|
replacement-blob-codec.ts # Content-addressed codec (sha256, fail-fast on absent)
|
|
82
84
|
replacement-hydrator.ts # Stripped state rehydration + capability interface
|
|
83
85
|
session-write-lease.ts # O_EXCL lockfile + token + heartbeat + stale takeover
|
|
@@ -85,7 +87,7 @@ src/
|
|
|
85
87
|
memory-persistence.ts # InMemory session persistence adapter
|
|
86
88
|
file-persistence.ts # File session persistence adapter (deprecated)
|
|
87
89
|
remote-persistence.ts # Remote HTTP session persistence adapter
|
|
88
|
-
message-bytes.ts #
|
|
90
|
+
message-bytes.ts # estimatedContentBytes + capStoredHistoryByBytes
|
|
89
91
|
constants.ts # Default limits
|
|
90
92
|
index.ts # Barrel exports
|
|
91
93
|
scripts/
|
|
@@ -108,14 +110,7 @@ pnpm vitest run packages/session/tests/
|
|
|
108
110
|
```
|
|
109
111
|
|
|
110
112
|
14 test files including:
|
|
111
|
-
- `
|
|
113
|
+
- `incident-replay-e2e`: replay of a real production data-loss incident (real disk DB, dual-process, zero-loss)
|
|
112
114
|
- `session-write-lease`: mutual exclusion / stale takeover / fencing
|
|
113
|
-
- `replacement-residency` + `replacement-blob-codec` + `
|
|
114
|
-
- `
|
|
115
|
-
|
|
116
|
-
## Related RFCs
|
|
117
|
-
|
|
118
|
-
- [RFC-037 Relational + append-only](../../docs/rfc/RFC-037-backend-database-relational-append.md)
|
|
119
|
-
- [RFC-159 Append-forever + write lease](../../docs/rfc/RFC-159-session-persistence-append-forever.md) (2026-07-13 postmortem)
|
|
120
|
-
- [RFC-160 Replacement residency](../../docs/rfc/RFC-160-compaction-replacement-residency.md) (blob dedup + residency data)
|
|
121
|
-
- [RFC-178 Content byte budget](../../docs/rfc/RFC-178-content-bytes-cap.md)
|
|
115
|
+
- `replacement-residency` + `replacement-blob-codec` + `replacement-integration-e2e`: strip/hydrate/dual-format/migration equivalence
|
|
116
|
+
- `content-bytes`: byte budget incremental counter + hard gate
|
package/dist/index.d.ts
CHANGED
|
@@ -52,6 +52,19 @@ interface SessionContext<T = unknown> {
|
|
|
52
52
|
*/
|
|
53
53
|
interface PersistedSessionConfig {
|
|
54
54
|
interactive?: boolean;
|
|
55
|
+
/**
|
|
56
|
+
* 是否在会话列表(`/resume`)中对用户可见。缺省(undefined)= 可见。
|
|
57
|
+
*
|
|
58
|
+
* `false` 用于**一次性内部会话**:headless `otto --print/--json` 单轮调用(含技能回路
|
|
59
|
+
* 探针、eval 评测 harness 等自举场景 spawn 出来的子进程)。这些会话必须照常落盘
|
|
60
|
+
* ——`runJsonMode` 的输出契约含 `sessionId`,eval 侧还要按 id 读 trace——但它们不是
|
|
61
|
+
* 用户的对话,出现在 `/resume` 里纯属噪音(生产实测:单个 workspace 积累 85 条)。
|
|
62
|
+
*
|
|
63
|
+
* 为什么不复用 `interactive`:`otto serve`/web-ui 创建的会话同样没有 `interactive`
|
|
64
|
+
* 标记,但那是**真实用户会话**,按 `interactive` 过滤会把它们一并误藏。可见性与
|
|
65
|
+
* 交互性是两个独立轴,故给独立字段。
|
|
66
|
+
*/
|
|
67
|
+
listable?: boolean;
|
|
55
68
|
depth?: number;
|
|
56
69
|
agentName?: string;
|
|
57
70
|
thinkingLevel?: string;
|
|
@@ -200,6 +213,21 @@ interface SessionMetadata {
|
|
|
200
213
|
pinGroup?: string;
|
|
201
214
|
config?: PersistedSessionConfig;
|
|
202
215
|
}
|
|
216
|
+
/**
|
|
217
|
+
* 面板态写入选项。
|
|
218
|
+
*
|
|
219
|
+
* `touch: false` = **纯装载**(restore 把已持久化的面板态填回内存),不是用户活动,
|
|
220
|
+
* 因而不得推进 `lastActiveAt`;缺省 `true`(回合内的真实面板更新,行为不变)。
|
|
221
|
+
*
|
|
222
|
+
* 为什么需要它:restore 还原完 metadata 后仍会经 `PanelStateRestorer` 用下列 setter
|
|
223
|
+
* 回填面板态,而每个 setter 各自 `lastActiveAt = Date.now()`,会把刚还原的真实活动
|
|
224
|
+
* 时间重新盖成当前时刻,并随下一次 save 永久写回 DB——`/resume` 列表时间戳全变
|
|
225
|
+
* "刚刚"、按时间排序失效的第二个来源(与 restore 主装载路径同源)。
|
|
226
|
+
*/
|
|
227
|
+
interface PanelWriteOptions {
|
|
228
|
+
/** 是否视为用户活动并推进 lastActiveAt。装载/回填路径应显式传 false。 */
|
|
229
|
+
touch?: boolean;
|
|
230
|
+
}
|
|
203
231
|
interface Session<T = unknown> {
|
|
204
232
|
id: string;
|
|
205
233
|
readonly leafId: string | undefined;
|
|
@@ -263,9 +291,9 @@ interface Session<T = unknown> {
|
|
|
263
291
|
* 迁至独立 panelState 字段。绝大多数消费点因此无需修改。
|
|
264
292
|
*/
|
|
265
293
|
getTodoList(): TodoItem[] | undefined;
|
|
266
|
-
setTodoList(todos: TodoItem[]): void;
|
|
294
|
+
setTodoList(todos: TodoItem[], options?: PanelWriteOptions): void;
|
|
267
295
|
getEditedFiles(): EditedFile[] | undefined;
|
|
268
|
-
setEditedFiles(files: EditedFile[]): void;
|
|
296
|
+
setEditedFiles(files: EditedFile[], options?: PanelWriteOptions): void;
|
|
269
297
|
/**
|
|
270
298
|
* 持久化输入历史(@deprecated RFC-088 M4b:移入 cli InputHistoryStore。
|
|
271
299
|
* 仅保留读取以兼容旧快照一次性迁移)。
|
|
@@ -277,20 +305,20 @@ interface Session<T = unknown> {
|
|
|
277
305
|
setInputHistory(entries: NonNullable<PersistedSessionConfig['inputHistory']>): void;
|
|
278
306
|
/** 子代理面板持久化(stat-only)。RFC-108 D3:存储迁至 panelState 独立字段。 */
|
|
279
307
|
getSubagents(): SubagentEntry[] | undefined;
|
|
280
|
-
setSubagents(entries: SubagentEntry[]): void;
|
|
308
|
+
setSubagents(entries: SubagentEntry[], options?: PanelWriteOptions): void;
|
|
281
309
|
/** 绝对回合总数(resume 末尾对齐派生 turnBoundaries)。 */
|
|
282
310
|
getTurnCount(): number | undefined;
|
|
283
311
|
setTurnCount(n: number): void;
|
|
284
312
|
/** 草稿面板持久化(DraftPane 的 Ctrl+S 保存/加载)。RFC-108 D3:存储迁至 panelState 独立字段。 */
|
|
285
313
|
getDrafts(): DraftEntry[] | undefined;
|
|
286
|
-
setDrafts(entries: DraftEntry[]): void;
|
|
314
|
+
setDrafts(entries: DraftEntry[], options?: PanelWriteOptions): void;
|
|
287
315
|
/**
|
|
288
316
|
* 回合完成摘要面板持久化(TUI 底部摘要行"✓ 完成 · N 个工具 · 耗时 · tokens · 模型")。
|
|
289
317
|
* 每回合累加写入(整表覆盖式 set,调用方 read-append-write),与 messages() 物理隔离,
|
|
290
318
|
* 不进 provider 请求——只供 resume 时按 turn 插回对话流重绘。
|
|
291
319
|
*/
|
|
292
320
|
getTurnSummaries(): TurnSummaryEntry[] | undefined;
|
|
293
|
-
setTurnSummaries(entries: TurnSummaryEntry[]): void;
|
|
321
|
+
setTurnSummaries(entries: TurnSummaryEntry[], options?: PanelWriteOptions): void;
|
|
294
322
|
}
|
|
295
323
|
interface SessionStore<T = unknown> {
|
|
296
324
|
createSession(id?: string): Promise<Session<T>>;
|
|
@@ -394,6 +422,39 @@ declare class InMemorySession<T = unknown> implements Session<T> {
|
|
|
394
422
|
constructor(id: string, parentSessionId?: string, forkPoint?: number);
|
|
395
423
|
private _leafId;
|
|
396
424
|
get leafId(): string | undefined;
|
|
425
|
+
/**
|
|
426
|
+
* **`lastActiveAt` 的唯一写入口。** 除本方法与 `restoreEntries`(按快照原样装载)外,
|
|
427
|
+
* 本类任何地方都不得直接赋值 `this.meta.lastActiveAt`——有架构门禁强制
|
|
428
|
+
* (`packages/session/tests/last-active-single-writer.test.ts`)。
|
|
429
|
+
*
|
|
430
|
+
* ## 为什么要收口(2026-08-13 生产数据损坏事故)
|
|
431
|
+
*
|
|
432
|
+
* 该字段会经 `save()` → `touchSession()` → `UPDATE sessions SET last_active_at = ?`
|
|
433
|
+
* **永久落盘**,是 `/resume` 列表的展示时间与排序键。事故现象:列表里几乎所有会话都
|
|
434
|
+
* 显示"N 秒前"、按时间排序完全失效,真实活动时间**不可逆丢失**。根因是多个"非活动"
|
|
435
|
+
* 路径也在写它,而每处单看都人畜无害:
|
|
436
|
+
* ① `restore`/`restoreAll` 装载快照时盖成 `Date.now()`(把"恢复"当成"活动");
|
|
437
|
+
* ② restore 下游的面板态回填逐个走 panel setter,每个 setter 各自 bump;
|
|
438
|
+
* ③ `/pin` `/archive` 等管理动作;④ 归档态回放触发的 `setArchived`。
|
|
439
|
+
* 每次启动 `restoreAll` 恢复池内会话(默认 50),就把它们集体盖成本次启动时刻。
|
|
440
|
+
*
|
|
441
|
+
* ## 判据:什么才算"活动"
|
|
442
|
+
*
|
|
443
|
+
* **活动 = 会话内容本身发生了变化**(用户/模型往这个会话里写了东西):
|
|
444
|
+
* `append`、`removeLast`、`compact`、`recordCompaction`、`clearContext`、`branch`。
|
|
445
|
+
*
|
|
446
|
+
* **不是活动**(即便它们也写持久化状态):
|
|
447
|
+
* - *装载/回填*:restore、面板态回填、一次性字段迁移——读取历史不该改写历史;
|
|
448
|
+
* - *管理动作*:`/pin` `/archive` `/rename`——它们改变的是会话的**元数据**,
|
|
449
|
+
* 而 `lastActiveAt` 回答的是"最后一次聊天是什么时候"。把管理动作算作活动,
|
|
450
|
+
* 会让"随手 pin 一下"把会话顶到 `/resume` 最前并改写其显示时间。
|
|
451
|
+
* - *派生记账*:`setTurnCount` 等由真实活动顺带触发的计数——真实活动自己已经
|
|
452
|
+
* `markActivity()` 过了,再 bump 一次只会让口径更难推理。
|
|
453
|
+
*
|
|
454
|
+
* 新增写入点前先归类;拿不准就**不要 touch**——漏 bump 只影响排序新鲜度(下一条
|
|
455
|
+
* 消息就会修正),错 bump 则永久污染数据且不可逆。
|
|
456
|
+
*/
|
|
457
|
+
private markActivity;
|
|
397
458
|
append(message: T): void;
|
|
398
459
|
/**
|
|
399
460
|
* RFC-283 D2:移除最后一条 message entry(内存态回滚)。
|
|
@@ -471,34 +532,61 @@ declare class InMemorySession<T = unknown> implements Session<T> {
|
|
|
471
532
|
/**
|
|
472
533
|
* RFC-078 R1/R2:单写路径 + 等级守卫。弱来源不得覆盖强来源
|
|
473
534
|
* (custom 永不被 ai/derived 盖;同级可覆盖,如 ai 重生覆盖旧 ai)。
|
|
535
|
+
*
|
|
536
|
+
* **不推进 `lastActiveAt`**(见 `markActivity` 的判据):改标题是给会话贴标签,
|
|
537
|
+
* 不是往会话里说话。三条来源没有一条构成"活动":
|
|
538
|
+
* - `derived`/`ai`:由真实消息顺带触发,那条消息自己已经 `markActivity()` 过了;
|
|
539
|
+
* - `custom`(`/rename`):与 `/pin` `/archive` 同属管理动作;
|
|
540
|
+
* - `backfillTitles()`(对**已有历史**的旧会话批量重生 ai 标题):若在此 bump,
|
|
541
|
+
* 一次批量回血就会把一堆冷会话的活动时间集体刷成当前时刻——与 restore 污染同型。
|
|
474
542
|
*/
|
|
475
543
|
setTitle(title: string, source: TitleSource): boolean;
|
|
476
544
|
/** 设置创建此会话的 SDK 版本(仅在新会话创建时调用一次)。 */
|
|
477
545
|
setSdkVersion(version: string): void;
|
|
478
|
-
/**
|
|
546
|
+
/**
|
|
547
|
+
* 归档状态持久化镜像写入(见 `Session.setArchived` 契约注释)。
|
|
548
|
+
*
|
|
549
|
+
* **不推进 `lastActiveAt`**:`/archive` 是对会话的管理动作,不是会话内的活动。
|
|
550
|
+
* 且 restore 会对归档快照回放一次 `archive()`(persistence-sync 的归档态回放),
|
|
551
|
+
* 若此处 bump,纯粹的"恢复"就会再次污染真实活动时间并随 save 落库。
|
|
552
|
+
*/
|
|
479
553
|
setArchived(archived: boolean): void;
|
|
480
|
-
/**
|
|
554
|
+
/**
|
|
555
|
+
* 置顶状态写入。`pinned=false` 时无条件清空 `pinGroup`(不保留旧分组,见 RFC-158 §4)。
|
|
556
|
+
*
|
|
557
|
+
* **不推进 `lastActiveAt`**:`/pin` 只改变 `/resume` 的排序权重与分组归属,
|
|
558
|
+
* 不是会话活动。此前 bump 会让"随手 pin 一下"把会话顶到列表最前、并改写其显示时间。
|
|
559
|
+
*/
|
|
481
560
|
setPinned(pinned: boolean, group?: string): void;
|
|
561
|
+
/**
|
|
562
|
+
* 面板 setter 的活动时间推进闸门:仅"真实面板更新"推进 `lastActiveAt`,
|
|
563
|
+
* 装载/回填(`{ touch: false }`)不推进。见 `PanelWriteOptions`。
|
|
564
|
+
*/
|
|
565
|
+
private touchIfActivity;
|
|
482
566
|
/** 获取持久化的任务面板状态。RFC-108 D3:存储迁至 panelState 独立字段。 */
|
|
483
567
|
getTodoList(): TodoItem[] | undefined;
|
|
484
568
|
/** 设置持久化的任务面板状态。RFC-108 D3:存储迁至 panelState 独立字段。 */
|
|
485
|
-
setTodoList(todos: TodoItem[]): void;
|
|
569
|
+
setTodoList(todos: TodoItem[], options?: PanelWriteOptions): void;
|
|
486
570
|
/** 获取持久化的编辑文件面板状态。RFC-108 D3:存储迁至 panelState 独立字段。 */
|
|
487
571
|
getEditedFiles(): EditedFile[] | undefined;
|
|
488
572
|
/** 设置持久化的编辑文件面板状态。max 50 条(最新在前)。RFC-108 D3:存储迁至 panelState。 */
|
|
489
|
-
setEditedFiles(files: EditedFile[]): void;
|
|
573
|
+
setEditedFiles(files: EditedFile[], options?: PanelWriteOptions): void;
|
|
490
574
|
/** 获取持久化的输入历史。 */
|
|
491
575
|
getInputHistory(): string[] | undefined;
|
|
492
576
|
/**
|
|
493
577
|
* 设置持久化的输入历史。max 100 条(最近在末尾)。config 为惰性对象,首次写入时初始化。
|
|
494
578
|
* @deprecated RFC-088 M4b:历史已移至 cli InputHistoryStore。本方法仅迁移路径调用——
|
|
495
579
|
* 传空数组 = **删除字段**(快照不留 `inputHistory: []` 残迹,对齐 M4b 设计"下次快照字段消失")。
|
|
580
|
+
*
|
|
581
|
+
* **不推进 `lastActiveAt`**:唯一存活调用点是启动期的一次性字段迁移
|
|
582
|
+
* (`cli/src/commands/interactive-history-setup.ts` 的 `setInputHistory([])`),
|
|
583
|
+
* 属"装载/迁移"而非会话活动——启动时清理旧字段不该把会话顶到 `/resume` 最前。
|
|
496
584
|
*/
|
|
497
585
|
setInputHistory(entries: string[]): void;
|
|
498
586
|
/** 获取持久化的子代理面板状态。RFC-108 D3:存储迁至 panelState 独立字段。 */
|
|
499
587
|
getSubagents(): SubagentEntry[] | undefined;
|
|
500
588
|
/** 设置持久化的子代理面板状态(stat-only)。max 100 条。RFC-108 D3:存储迁至 panelState。 */
|
|
501
|
-
setSubagents(entries: SubagentEntry[]): void;
|
|
589
|
+
setSubagents(entries: SubagentEntry[], options?: PanelWriteOptions): void;
|
|
502
590
|
/** 获取持久化的回合完成摘要列表(TUI 底部摘要行)。 */
|
|
503
591
|
getTurnSummaries(): TurnSummaryEntry[] | undefined;
|
|
504
592
|
/**
|
|
@@ -506,15 +594,21 @@ declare class InMemorySession<T = unknown> implements Session<T> {
|
|
|
506
594
|
* read-append-write)。上限对齐 todoList/subagents 同类"面板态防无界增长"纪律;
|
|
507
595
|
* 200 远超单会话正常回合数,仅作防御性上限,不做"只留最近 N 条"这类会丢历史的裁剪。
|
|
508
596
|
*/
|
|
509
|
-
setTurnSummaries(entries: TurnSummaryEntry[]): void;
|
|
597
|
+
setTurnSummaries(entries: TurnSummaryEntry[], options?: PanelWriteOptions): void;
|
|
510
598
|
/** 获取持久化的绝对回合总数。 */
|
|
511
599
|
getTurnCount(): number | undefined;
|
|
512
|
-
/**
|
|
600
|
+
/**
|
|
601
|
+
* 设置持久化的绝对回合总数。config 惰性初始化。
|
|
602
|
+
*
|
|
603
|
+
* **不推进 `lastActiveAt`**:回合计数是真实活动的**派生记账**——推进它的那些消息
|
|
604
|
+
* 自己已经 `markActivity()` 过了,这里再 bump 只是重复,且让"谁有权推进活动时间"
|
|
605
|
+
* 的口径变模糊(见 `markActivity` 判据)。
|
|
606
|
+
*/
|
|
513
607
|
setTurnCount(n: number): void;
|
|
514
608
|
/** 获取持久化的草稿列表。RFC-108 D3:存储迁至 panelState 独立字段。 */
|
|
515
609
|
getDrafts(): DraftEntry[] | undefined;
|
|
516
610
|
/** 设置持久化的草稿列表。max 50 条(对齐迁移前 DraftStore 上限)。RFC-108 D3:存储迁至 panelState。 */
|
|
517
|
-
setDrafts(entries: DraftEntry[]): void;
|
|
611
|
+
setDrafts(entries: DraftEntry[], options?: PanelWriteOptions): void;
|
|
518
612
|
/**
|
|
519
613
|
* 把存储的会话历史封顶到最近 maxMessages 条(删最早的消息条目,compaction/clear 边界不参与
|
|
520
614
|
* 计数、不被裁)。调用后 messageCount 重新派生。
|
|
@@ -1281,5 +1375,5 @@ declare class RemoteSessionPersistence<T = unknown> extends RemotePersistence<Se
|
|
|
1281
1375
|
listRecentMeta(limit: number): Promise<string[]>;
|
|
1282
1376
|
}
|
|
1283
1377
|
//#endregion
|
|
1284
|
-
export { type DraftEntry, type EditedFile, type EntryInput, type EntryRow, FileSessionPersistence, type FileSessionPersistenceOptions, InMemorySession, InMemorySessionPersistence, InMemorySessionStore, type LeaseInspection, type PaginationOptions, type PersistedSessionConfig, type ReassembleOptions, RelationalSessionPersistence, RemotePersistenceError, RemoteSessionPersistence, type RemoteSessionPersistenceOptions, RemoteSnapshotConflictError, type ReplacementHydrationCapable, SESSION_IDLE_TIMEOUT_MS, SESSION_MAX, SESSION_MIGRATIONS, SESSION_PAGE_SIZE, SESSION_SNAPSHOT_VERSION, type Session, type SessionContext, type SessionEntry, type SessionEntryType, type SessionMetadata, type SessionPersistence, type SessionRepository, type SessionRow, type SessionSnapshot, type SessionStore, SessionWriteLeaseDeniedError, type SessionWriteLeaseManager, type SessionWriteLeaseOptions, SqliteSessionRepository, type SqliteSessionRepositoryOptions, type SubagentEntry, type TodoItem, type TurnSummaryEntry, type WorkspaceRow, createInMemorySessionStore, createNoopSessionWriteLeaseManager, createSessionWriteLeaseManager, decodeReplacementFromBlobs, encodeReplacementToBlobs, entryToInput, estimateMessageContentBytes, explodeSnapshot, hasStrippedReplacements, hashMessageContent, hydrateStrippedReplacements, reassembleSnapshot, sessionRowFromSnapshot, supportsReplacementHydration };
|
|
1378
|
+
export { type DraftEntry, type EditedFile, type EntryInput, type EntryRow, FileSessionPersistence, type FileSessionPersistenceOptions, InMemorySession, InMemorySessionPersistence, InMemorySessionStore, type LeaseInspection, type PaginationOptions, type PanelWriteOptions, type PersistedSessionConfig, type ReassembleOptions, RelationalSessionPersistence, RemotePersistenceError, RemoteSessionPersistence, type RemoteSessionPersistenceOptions, RemoteSnapshotConflictError, type ReplacementHydrationCapable, SESSION_IDLE_TIMEOUT_MS, SESSION_MAX, SESSION_MIGRATIONS, SESSION_PAGE_SIZE, SESSION_SNAPSHOT_VERSION, type Session, type SessionContext, type SessionEntry, type SessionEntryType, type SessionMetadata, type SessionPersistence, type SessionRepository, type SessionRow, type SessionSnapshot, type SessionStore, SessionWriteLeaseDeniedError, type SessionWriteLeaseManager, type SessionWriteLeaseOptions, SqliteSessionRepository, type SqliteSessionRepositoryOptions, type SubagentEntry, type TodoItem, type TurnSummaryEntry, type WorkspaceRow, createInMemorySessionStore, createNoopSessionWriteLeaseManager, createSessionWriteLeaseManager, decodeReplacementFromBlobs, encodeReplacementToBlobs, entryToInput, estimateMessageContentBytes, explodeSnapshot, hasStrippedReplacements, hashMessageContent, hydrateStrippedReplacements, reassembleSnapshot, sessionRowFromSnapshot, supportsReplacementHydration };
|
|
1285
1379
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/in-memory-session.ts","../src/message-bytes.ts","../src/store.ts","../src/memory-persistence.ts","../src/file-persistence.ts","../src/session-repository.ts","../src/session-write-lease.ts","../src/relational-session-persistence.ts","../src/relational-bridge.ts","../src/replacement-blob-codec.ts","../src/replacement-hydrator.ts","../src/constants.ts","../src/sqlite-session-repository.ts","../src/remote-persistence.ts"],"mappings":";;;KAIY,YAAA;EACN,IAAA;EAAiB,EAAA;EAAY,QAAA;EAAmB,OAAA,EAAS,CAAA;EAAG,SAAA;AAAA;EAE5D,IAAA;EACA,EAAA;EACA,QAAA;EACA,OAAA;EACA,cAAA;EAJA;;;;;;EAWA,WAAA,GAAc,CAAA;EAOd;;;;;;EAAA,mBAAA;EACA,SAAA;AAAA;;;;;;;;EAQA,IAAA;EAAe,EAAA;EAAY,QAAA;EAAmB,SAAA;AAAA;AAAA,UAEnC,cAAA;EACf,OAAA;EACA,QAAA,EAAU,CAAA;AAAA;;;;;;UAQK,sBAAA;EACf,WAAA;EACA,KAAA;EACA,SAAA;EACA,aAAA;EACA,qBAAA;EACA,SAAA;EAyCS;EAvCT,OAAA;EA6CyB;;;;EAxCzB,YAAA;EA2CA;EAzCA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KAAqB,OAAA;EAYnE,QAAA,CAAS,MAAA,sBAA4B,OAAA,CAAQ,GAAA;EAW7C,gBAAA,CAAiB,SAAA,UAAmB,QAAA,sBAA8B,OAAA,CAAQ,QAAA;EbzchF;;;;;EAAA,Qa6dS,YAAA;AAAA;;;UCtkBM,+BAAA;EACf,OAAA;EACA,OAAA,QAAe,OAAA;IAAU,KAAA;EAAA;EACzB,UAAA,SAAmB,OAAA,CAAQ,MAAA;EAC3B,KAAA,SAAc,UAAA,CAAW,KAAA;EACzB,SAAA;EdNoD;EcQpD,MAAA;EdRgE;;;;;;;;;;EcmBhE,KAAA;AAAA;AAAA,cAGW,wBAAA,sBACH,iBAAA,CAAkB,eAAA,CAAgB,CAAA,cAC/B,kBAAA,CAAmB,CAAA;EdKoB;;;AAEpD;;EAFoD,ScEzC,SAAA;cAEG,OAAA,EAAS,+BAAA;EAAA,cAkBE,YAAA,CAAA;EAAA,cAGA,YAAA,CAAA;EAAA,UAIJ,SAAA,CAAU,QAAA,EAAU,eAAA,CAAgB,CAAA;EdzB7C;;;AAQZ;;;Ec2BQ,cAAA,CAAe,KAAA,WAAgB,OAAA;AAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/in-memory-session.ts","../src/message-bytes.ts","../src/store.ts","../src/memory-persistence.ts","../src/file-persistence.ts","../src/session-repository.ts","../src/session-write-lease.ts","../src/relational-session-persistence.ts","../src/relational-bridge.ts","../src/replacement-blob-codec.ts","../src/replacement-hydrator.ts","../src/constants.ts","../src/sqlite-session-repository.ts","../src/remote-persistence.ts"],"mappings":";;;KAIY,YAAA;EACN,IAAA;EAAiB,EAAA;EAAY,QAAA;EAAmB,OAAA,EAAS,CAAA;EAAG,SAAA;AAAA;EAE5D,IAAA;EACA,EAAA;EACA,QAAA;EACA,OAAA;EACA,cAAA;EAJA;;;;;;EAWA,WAAA,GAAc,CAAA;EAOd;;;;;;EAAA,mBAAA;EACA,SAAA;AAAA;;;;;;;;EA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AC/B,kBAAA,CAAmB,CAAA;EdKoB;;;AAEpD;;EAFoD,ScEzC,SAAA;cAEG,OAAA,EAAS,+BAAA;EAAA,cAkBE,YAAA,CAAA;EAAA,cAGA,YAAA,CAAA;EAAA,UAIJ,SAAA,CAAU,QAAA,EAAU,eAAA,CAAgB,CAAA;EdzB7C;;;AAQZ;;;Ec2BQ,cAAA,CAAe,KAAA,WAAgB,OAAA;AAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{DiskPersistence as e,MemoryPersistenceBase as t,RemotePersistence as n,RemotePersistenceError as r,RemoteSnapshotConflictError as i,acquireDb as a,releaseDb as o}from"@x-otto/persistence";import{currentHostname as s,decodeLeaseToken as c,encodeLeaseToken as l,isProcessAlive as u,normalizeEnv as d}from"@x-otto/env";import{readFile as f,readdir as p,stat as m}from"node:fs/promises";import{dirname as h,join as g,resolve as _}from"node:path";import{createHash as v,randomUUID as y}from"node:crypto";import{closeSync as b,createWriteStream as x,existsSync as S,mkdirSync as C,openSync as ee,readFileSync as w,renameSync as T,rmSync as E,statSync as D,unlinkSync as O,utimesSync as te,writeSync as k}from"node:fs";import{createGzip as A,gunzipSync as j}from"node:zlib";const M={derived:0,ai:1,custom:2};function N(e){if(typeof e!=`object`||!e)return 0;let t=e,n=0,r=t.tool_calls;if(Array.isArray(r))for(let e of r){if(typeof e!=`object`||!e)continue;let t=e.function;t&&typeof t==`object`&&typeof t.arguments==`string`&&(n+=t.arguments.length)}let i=t.content;if(typeof i==`string`)return n+i.length;if(!Array.isArray(i))return n;for(let e of i){if(typeof e!=`object`||!e)continue;let t=e;typeof t.text==`string`&&(n+=t.text.length);let r=t.source;r&&typeof r==`object`&&typeof r.data==`string`&&(n+=r.data.length),typeof t.data==`string`&&(n+=t.data.length);let i=t.image_url;i&&typeof i==`object`&&typeof i.url==`string`&&(n+=i.url.length),t.type===`tool_call`&&typeof t.arguments==`object`&&t.arguments!=null&&(n+=JSON.stringify(t.arguments).length),t.type===`tool_use`&&t.input!=null&&(n+=JSON.stringify(t.input).length)}return n}var P=class{sessionEntries=[];entryMap=new Map;_estimatedContentBytes=0;get estimatedContentBytes(){return this._estimatedContentBytes}get messageCount(){return this.meta.messageCount}verifyEstimatedContentBytes(){let e=0;for(let t of this.sessionEntries)if(t.type===`message`)e+=N(t.message);else if(t.type===`compaction`&&t.replacement)for(let n of t.replacement)e+=N(n);return{counter:this._estimatedContentBytes,recomputed:e,drift:e-this._estimatedContentBytes}}meta;panelState={};constructor(e,t,n){this.id=e;let r=Date.now();this.meta={createdAt:r,lastActiveAt:r,messageCount:0,compactionCount:0,parentSessionId:t,forkPoint:n,tags:[]}}_leafId=void 0;get leafId(){return this._leafId}append(e){let t={type:`message`,id:crypto.randomUUID(),parentId:this._leafId,message:e,timestamp:Date.now()};this._leafId=t.id,this.sessionEntries.push(t),this.entryMap.set(t.id,t),this.meta.messageCount++,this.meta.lastActiveAt=Date.now(),this._estimatedContentBytes+=N(e)}removeLast(){if(!this._leafId)return;let e=this.entryMap.get(this._leafId);if(!e||e.type!==`message`)return;let t=this.sessionEntries.lastIndexOf(e);t!==-1&&(this.sessionEntries.splice(t,1),this.entryMap.delete(e.id),this._leafId=e.parentId,this.meta.messageCount=Math.max(0,this.meta.messageCount-1),this._estimatedContentBytes-=N(e.message))}compact(e,t){let n=this.getBranchMessageEntries();if(t<=0||t>n.length)return;let r={type:`compaction`,id:crypto.randomUUID(),parentId:this._leafId,summary:e,compactedCount:t,timestamp:Date.now()};this.sessionEntries.push(r),this.entryMap.set(r.id,r),this.meta.compactionCount++,this.meta.lastActiveAt=Date.now(),this._leafId=r.id}recordCompaction(e,t){let n=this.findActiveCompaction(),r={type:`compaction`,id:crypto.randomUUID(),parentId:this._leafId,summary:e,compactedCount:t.length,replacement:[...t],timestamp:Date.now()};for(let e of t)this._estimatedContentBytes+=N(e);this.sessionEntries.push(r),this.entryMap.set(r.id,r),this.meta.compactionCount++,this.meta.lastActiveAt=Date.now(),this._leafId=r.id,n&&n.replacement!=null&&this.replacementStripEligibility?.(n.id)===!0&&this.stripReplacementInPlace(n.id)}replacementStripEligibility;setReplacementStripEligibility(e){this.replacementStripEligibility=e}findActiveCompaction(){return this._leafId?this.findActiveCompactionFrom(this._leafId):void 0}stripReplacementInPlace(e){let t=this.entryMap.get(e);if(!t||t.type!==`compaction`)return;let n=t;if(n.replacement==null)return;for(let e of n.replacement)this._estimatedContentBytes-=N(e);this._estimatedContentBytes<0&&(this._estimatedContentBytes=0);let{replacement:r,...i}=n,a={...i,replacementStripped:!0};this.entryMap.set(e,a);let o=this.sessionEntries.findIndex(t=>t.id===e);o>=0&&(this.sessionEntries[o]=a)}clearContext(e){let t={type:`clear`,id:crypto.randomUUID(),parentId:this._leafId,timestamp:Date.now()};this.sessionEntries.push(t),this.entryMap.set(t.id,t),this.meta.lastActiveAt=Date.now(),this._leafId=t.id,e?.purge===!0&&this.purgeBeforeBoundary(t.id)}purgeClearedHistory(){let e;for(let t=this.sessionEntries.length-1;t>=0;t--)if(this.sessionEntries[t].type===`clear`){e=this.sessionEntries[t].id;break}return e?this.purgeBeforeBoundary(e):{removedCount:0,strippedReplacements:0}}purgeBeforeBoundary(e){let t=this.sessionEntries.findIndex(t=>t.id===e);if(t<0)return{removedCount:0,strippedReplacements:0};let n=0,r=0,i=0,a=t;for(;r<a;){let e=this.sessionEntries[r];e.type===`message`?(this._estimatedContentBytes-=N(e.message),this.entryMap.delete(e.id),this.sessionEntries.splice(r,1),a--,i++):(e.type===`compaction`&&e.replacement!=null&&(this.stripReplacementInPlace(e.id),n++),r++)}return this._estimatedContentBytes<0&&(this._estimatedContentBytes=0),this.meta.messageCount-=i,{removedCount:i,strippedReplacements:n}}branch(e){if(!this.entryMap.has(e))throw Error(`Entry "${e}" not found in session "${this.id}"`);let t=this.findActiveCompactionFrom(e);if(t&&t.replacementStripped)throw Error(`branch: target chain's active compaction boundary "${t.id}" has a stripped replacement (RFC-160); hydrate it via loadEntriesByIds before branching`);this._leafId=e,this.meta.lastActiveAt=Date.now()}findActiveCompactionFrom(e){let t=new Set,n=this.entryMap.get(e);for(;n&&!t.has(n.id);){if(t.add(n.id),n.type===`compaction`)return n;if(n.type===`clear`)return;n=n.parentId?this.entryMap.get(n.parentId):void 0}}entries(){return this.sessionEntries}branchEntries(){return this.walkBranch()}buildContext(){let e=this.walkBranch(),t=this.lastBoundaryIndex(e),n=e.slice(t+1).filter(e=>e.type===`message`).map(e=>e.message);if(t===-1)return{messages:n};let r=e[t];if(r.type===`clear`)return{messages:n};let i=r;return{summary:i.summary,messages:i.replacement?[...i.replacement,...n]:n}}messages(){return this.walkBranch().filter(e=>e.type===`message`).map(e=>e.message)}visibleMessages(){let e=this.walkBranch(),t=-1;for(let n=e.length-1;n>=0;n--)if(e[n]?.type===`clear`){t=n;break}return e.slice(t+1).filter(e=>e.type===`message`).map(e=>e.message)}metadata(){return{...this.meta,tags:[...this.meta.tags],...this.meta.config?{config:structuredClone(this.meta.config)}:{}}}setTitle(e,t){let n=this.meta.titleSource==null?-1:M[this.meta.titleSource];return M[t]<n?!1:(this.meta.title=e,this.meta.titleSource=t,this.meta.lastActiveAt=Date.now(),!0)}setSdkVersion(e){this.meta.sdkVersion=e}setArchived(e){this.meta.archived=e,this.meta.lastActiveAt=Date.now()}setPinned(e,t){this.meta.pinned=e,this.meta.pinGroup=e?t:void 0,this.meta.lastActiveAt=Date.now()}getTodoList(){return this.panelState.todoList}setTodoList(e){this.panelState.todoList=[...e],this.meta.lastActiveAt=Date.now()}getEditedFiles(){return this.panelState.editedFiles}setEditedFiles(e){this.panelState.editedFiles=e.slice(0,50),this.meta.lastActiveAt=Date.now()}getInputHistory(){return this.meta.config?.inputHistory}setInputHistory(e){if(e.length===0){this.meta.config?.inputHistory!==void 0&&(delete this.meta.config.inputHistory,this.meta.lastActiveAt=Date.now());return}this.meta.config||(this.meta.config={}),this.meta.config.inputHistory=e.slice(-100),this.meta.lastActiveAt=Date.now()}getSubagents(){return this.panelState.subagents}setSubagents(e){this.panelState.subagents=e.slice(0,100),this.meta.lastActiveAt=Date.now()}getTurnSummaries(){return this.panelState.turnSummaries}setTurnSummaries(e){this.panelState.turnSummaries=e.slice(-200),this.meta.lastActiveAt=Date.now()}getTurnCount(){return this.meta.config?.turnCount}setTurnCount(e){this.meta.config||(this.meta.config={}),this.meta.config.turnCount=e,this.meta.lastActiveAt=Date.now()}getDrafts(){return this.panelState.drafts}setDrafts(e){this.panelState.drafts=e.slice(0,50),this.meta.lastActiveAt=Date.now()}capStoredHistory(e,t){let n=0;for(let e of this.sessionEntries)e.type===`message`&&n++;if(n<=e)return{capped:!1,removedCount:0,boundaryLimited:!1,activeOversized:!1};let r=n-e,{removed:i,boundaryLimited:a}=this.removeOldestMessages(r,t);return this.meta.messageCount=n-i,{capped:i>0,removedCount:i,boundaryLimited:a,activeOversized:this.meta.messageCount>e}}wouldTrimTouchActiveContext(e){let t=this.meta.messageCount;if(t<=e)return!1;let n=t-e,r=this.findActiveCompaction()?.id;if(r===void 0)return!0;let i=0;for(let e of this.sessionEntries){if(e.id===r)break;e.type===`message`&&i++}return i<n}wouldByteTrimTouchActiveContext(e){if(e<=0||this._estimatedContentBytes<=e)return!1;let t=this.findActiveCompaction()?.id;if(t===void 0)return!0;let n=0;for(let e of this.sessionEntries){if(e.id===t)break;e.type===`message`&&(n+=N(e.message))}return this._estimatedContentBytes-n>e}capStoredHistoryByBytes(e,t){if(e<=0||this._estimatedContentBytes<=e)return{capped:!1,removedCount:0,boundaryLimited:!1,activeOversized:!1};let n=0;for(let e of this.sessionEntries)e.type===`message`&&n++;let r=this._estimatedContentBytes,i=0;for(let t of this.sessionEntries){if(r<=e||i>=n-1)break;t.type===`message`&&(r-=N(t.message),i++)}if(i===0)return{capped:!1,removedCount:0,boundaryLimited:!1,activeOversized:!1};let{removed:a,boundaryLimited:o}=this.removeOldestMessages(i,t);return this.meta.messageCount=n-a,{capped:a>0,removedCount:a,boundaryLimited:o,activeOversized:this._estimatedContentBytes>e}}removeOldestMessages(e,t){let n=this.findActiveCompaction()?.id,r=!1,i=0,a=0;for(;a<this.sessionEntries.length&&i<e;){let e=this.sessionEntries[a];if(n!==void 0&&e.id===n){r=!0;break}e.type===`message`?(this._estimatedContentBytes-=N(e.message),this.entryMap.delete(e.id),this.sessionEntries.splice(a,1),i++):a++}if(t)for(;a<this.sessionEntries.length;){let e=this.sessionEntries[a];if(n!==void 0&&e.id===n){r=!0;break}if(e.type!==`message`){a++;continue}if(t(e.message))break;this._estimatedContentBytes-=N(e.message),this.entryMap.delete(e.id),this.sessionEntries.splice(a,1),i++}return this._estimatedContentBytes<0&&(this._estimatedContentBytes=0),{removed:i,boundaryLimited:r}}setTags(e){this.meta.tags=[...e]}addTag(e){this.meta.tags.includes(e)||this.meta.tags.push(e)}restoreEntries(e,t,n){this.sessionEntries.length=0,this.entryMap.clear();let r=0;for(let t of e)if(this.sessionEntries.push(t),this.entryMap.set(t.id,t),t.type===`message`)r+=N(t.message);else if(t.type===`compaction`&&t.replacement)for(let e of t.replacement)r+=N(e);this._estimatedContentBytes=r,Object.assign(this.meta,t),this._leafId=n&&this.entryMap.has(n)?n:e.length>0?e[e.length-1]?.id:void 0}toSnapshot(){return{entries:[...this.sessionEntries],metadata:this.metadata(),leafId:this._leafId}}walkBranch(){if(!this._leafId)return[];let e=[],t=new Set,n=this.entryMap.get(this._leafId);for(;n&&!t.has(n.id);)t.add(n.id),e.push(n),n=n.parentId?this.entryMap.get(n.parentId):void 0;return e.reverse(),e}getBranchMessageEntries(){let e=this.walkBranch(),t=this.lastBoundaryIndex(e);return e.slice(t+1).filter(e=>e.type===`message`)}lastBoundaryIndex(e){for(let t=e.length-1;t>=0;t--){let n=e[t]?.type;if(n===`compaction`||n===`clear`)return t}return-1}},F=class{sessions=new Map;async createSession(e=crypto.randomUUID()){let t=new P(e);return this.sessions.set(e,t),t}getSession(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values())}listSessionsPaginated(e){let{page:t,sortBy:n=`lastActiveAt`,order:r=`desc`}=e,i=e.pageSize??50,a=Array.from(this.sessions.values());a.sort((e,t)=>{let i=e.metadata(),a=t.metadata(),o=n===`createdAt`?i.createdAt:i.lastActiveAt,s=n===`createdAt`?a.createdAt:a.lastActiveAt;return r===`asc`?o-s:s-o});let o=a.length,s=Math.max(1,Math.ceil(o/i)),c=Math.max(0,Math.min(t,s-1)),l=c*i;return{items:a.slice(l,l+i),total:o,page:c,pageSize:i,totalPages:s,hasNext:c<s-1,hasPrevious:c>0}}async deleteSession(e){return this.sessions.delete(e)}async forkSession(e,t=crypto.randomUUID()){let n=this.sessions.get(e);if(!n)return;let r=n.toSnapshot(),i=new P(t,e,r.entries.length);return i.restoreEntries([...r.entries],{...r.metadata,createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:e,forkPoint:r.entries.length,tags:[...r.metadata.tags,`fork`]},r.leafId),this.sessions.set(t,i),i}};function ne(){return new F}const re=d(process.env.OTTO_SESSION_IDLE_TIMEOUT_MS,1800*1e3),ie=d(process.env.OTTO_SESSION_MAX,50),I=d(process.env.OTTO_SESSION_PAGE_SIZE,20),ae=d(process.env.OTTO_SESSION_SNAPSHOT_VERSION,1);var oe=class extends t{constructor(){super({defaultPageSize:I,defaultSortBy:`lastActiveAt`})}extractId(e){return e.id}getSortValue(e,t){return t===`createdAt`?e.metadata.createdAt:e.metadata.lastActiveAt}async listRecentMeta(e){return this.entries().filter(([,e])=>!e.metadata.archived).sort(([,e],[,t])=>t.metadata.lastActiveAt-e.metadata.lastActiveAt).slice(0,e).map(([e])=>e)}},se=class extends e{turnFlush=`snapshot`;sessionBaseDir;sessionExtension=`.session.json`;constructor(e){super({baseDir:e.baseDir,extension:`.session.json`,defaultPageSize:I}),this.sessionBaseDir=e.baseDir}extractId(e){return e.id}async listRecentMeta(e){let t;try{t=await p(this.sessionBaseDir)}catch{return[]}let n=t.filter(e=>e.endsWith(this.sessionExtension)),r=await Promise.all(n.map(async e=>{let t=await m(g(this.sessionBaseDir,e)).catch(()=>null);return{id:decodeURIComponent(e.slice(0,-this.sessionExtension.length)),mtime:t?.mtimeMs??0}}));r.sort((e,t)=>t.mtime-e.mtime);let i=[];for(let{id:t}of r){if(i.length>=e)break;let n=await this.load(t).catch(()=>null);n&&(n.metadata.archived||i.push(t))}return i}};function L(e){return`sha256:${v(`sha256`).update(e,`utf-8`).digest(`hex`)}`}async function R(e,t,n){if(e!==`compaction`)return t;let r=t.replacement;if(!Array.isArray(r))return t;let i=r.map(e=>JSON.stringify(e)),a=i.map(L);await n.putBlobs(i.map((e,t)=>({hash:a[t],content:e})));let{replacement:o,...s}=t;return{...s,replacementHashes:a}}async function z(e,t,n){if(e!==`compaction`)return t;let r=t.replacementHashes;if(!Array.isArray(r)||r.length===0){if(Array.isArray(r)){let{replacementHashes:e,...n}=t;return{...n,replacement:[]}}return t}let i=await n.getBlobs(r),a=r.map(e=>{let t=i.get(e);if(t==null)throw Error(`decodeReplacementFromBlobs: blob ${e} missing from message_blobs (corrupted import/partial backup?); refusing to assemble a lossy replacement (RFC-160 D7)`);return JSON.parse(t)}),{replacementHashes:o,...s}=t;return{...s,replacement:a}}function B(e,t){let n=e.metadata;return{id:e.id,workspaceKey:t,...n.title==null?{}:{title:n.title},...n.titleSource==null?{}:{titleSource:n.titleSource},...n.parentSessionId==null?{}:{parentSessionId:n.parentSessionId},...n.forkPoint==null?{}:{forkPoint:n.forkPoint},...e.leafId==null?{}:{leafId:e.leafId},tags:n.tags??[],...n.config==null?{}:{config:n.config},createdAt:n.createdAt,lastActiveAt:n.lastActiveAt,...n.archived==null?{}:{archived:n.archived},...n.pinned==null?{}:{pinned:n.pinned},...n.pinGroup==null?{}:{pinGroup:n.pinGroup}}}function V(e){let{type:t,id:n,parentId:r,timestamp:i,...a}=e;return{entryId:n,...r==null?{}:{parentId:r},type:t,data:a,createdAt:i}}function H(e){return{type:e.type,id:e.entryId,...e.parentId==null?{}:{parentId:e.parentId},timestamp:e.createdAt,...e.data}}async function U(e,t,n){await n.createSession(B(e,t));for(let t of e.entries)await n.appendEntry(e.id,V(t));await n.touchSession(e.id,e.leafId,e.metadata.lastActiveAt,e.metadata.title,e.metadata.titleSource,e.metadata.config,e.metadata.archived,e.metadata.pinned,e.metadata.pinGroup)}async function W(e,t,n){let r=await t.getSession(e);if(!r)return null;let i,a=!1;n?.maxEntries==null?i=(await t.loadEntries(e)).map(e=>H(e)):await t.getEntryCount(e)>n.maxEntries?(i=(await t.loadTailEntries(e,n.maxEntries)).map(e=>H(e)),a=!0,n.canStartHistory&&(i=le(i,n.canStartHistory))):i=(await t.loadEntries(e)).map(e=>H(e)),n?.stripInactiveReplacements?(i=ce(i,r.leafId??void 0),i=await G(i,t,{onlyUnstripped:!0})):i=await G(i,t,{onlyUnstripped:!1});let o=a?await t.countEntriesByType(e,`message`):i.filter(e=>e.type===`message`).length,s=a?await t.countEntriesByType(e,`compaction`):i.filter(e=>e.type===`compaction`).length,c={createdAt:r.createdAt,lastActiveAt:r.lastActiveAt,messageCount:o,compactionCount:s,tags:r.tags,...r.title==null?{}:{title:r.title},...r.titleSource==null?{}:{titleSource:r.titleSource},...r.parentSessionId==null?{}:{parentSessionId:r.parentSessionId},...r.forkPoint==null?{}:{forkPoint:r.forkPoint},...r.config==null?{}:{config:r.config},...r.archived==null?{}:{archived:r.archived},...r.pinned==null?{}:{pinned:r.pinned},...r.pinGroup==null?{}:{pinGroup:r.pinGroup}};return{version:1,id:e,entries:i,metadata:c,...r.leafId==null?{}:{leafId:r.leafId}}}async function G(e,t,n){let r=[];for(let i of e){let e=i;if(e.type!==`compaction`||e.replacementHashes==null){r.push(i);continue}if(n.onlyUnstripped&&e.replacementStripped){let{replacementHashes:t,...n}=e;r.push(n);continue}let{replacementStripped:a,...o}=await z(`compaction`,e,t);r.push(o)}return r}function ce(e,t){let n=new Map;for(let t of e)n.set(t.id,t);let r,i=new Set,a=t?n.get(t):void 0;for(;a&&!i.has(a.id);){if(i.add(a.id),a.type===`compaction`){r=a.id;break}if(a.type===`clear`)break;a=a.parentId?n.get(a.parentId):void 0}let o=-1;for(let t=e.length-1;t>=0;t--)if(e[t].type===`compaction`){o=t;break}return e.map((e,t)=>{if(e.type!==`compaction`||e.id===r||t===o)return e;let n=e;if(n.replacement!=null){let{replacement:e,...t}=n;return{...t,replacementStripped:!0}}return n.replacementHashes==null?e:{...n,replacementStripped:!0}})}function le(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r.type!==`message`||t(r.message))break;n++}return n>0?e.slice(n):e}function ue(e){return typeof e?.hydrateReplacements==`function`}function de(e){return e.some(e=>e.type===`compaction`&&e.replacementStripped)}async function K(e,t,n){let r=t.filter(e=>e.type===`compaction`&&e.replacementStripped).map(e=>e.id);if(r.length===0)return[...t];let i=await n.loadEntriesByIds(e,r),a=new Map;for(let e of i)a.set(e.entryId,e.data);let o=[];for(let r of t){if(r.type!==`compaction`||!r.replacementStripped){o.push(r);continue}let t=a.get(r.id);if(t&&t.replacementHashes!=null&&(t=await z(`compaction`,t,n)),!t||t.replacement==null)throw Error(`hydrateStrippedReplacements: authoritative row for compaction "${r.id}" in session "${e}" is missing or has no replacement (corrupted import?); refusing to continue with stripped state (RFC-160 rule 3)`);let{replacementStripped:i,...s}=r;o.push({...s,replacement:t.replacement})}return o}var q=class extends Error{constructor(e){super(`Session write lease denied for ${e}: another live process owns the write lease (this process is read-only for the session; refusing to save — RFC-159 D3)`),this.sessionId=e,this.name=`SessionWriteLeaseDeniedError`}};function J(e){let t=e.staleMs??6e4,n=e.renewEveryMs??1e4,r=new Map,i=!1,a=s(),o=t=>g(e.lockDir,`${t}.lock`),d=e=>{try{return c(w(o(e),`utf-8`).trim())}catch{return null}},f=e=>d(e)?.token??null,p=(t,n)=>{try{C(e.lockDir,{recursive:!0});let r=ee(o(t),`wx`);try{k(r,l(n,process.pid,a))}finally{b(r)}return!0}catch(e){if(e.code!==`EEXIST`)throw e;return!1}},m=e=>e.pid===void 0||e.host===void 0||e.host!==a?!1:!u(e.pid),h=e=>e.pid===void 0||e.host===void 0||e.host!==a?!1:u(e.pid),_=(e,t)=>{let i=setInterval(()=>{if(f(e)!==t){v(e);return}try{let t=new Date;te(o(e),t,t)}catch{v(e)}},n);i.unref(),r.set(e,{token:t,timer:i})},v=e=>{let t=r.get(e);t&&(clearInterval(t.timer),r.delete(e))},x={acquire(e){if(i)return!1;let n=r.get(e);if(n){if(f(e)===n.token)return!0;v(e)}let a=y();if(p(e,a))return _(e,a),!0;let s=d(e),c;try{c=D(o(e)).mtimeMs}catch{return p(e,a)?(_(e,a),!0):!1}if(s!==null&&h(s)||!(s!==null&&m(s))&&Date.now()-c<=t)return!1;let l=`${o(e)}.stale-${y()}`;try{T(o(e),l),E(l,{force:!0})}catch{return!1}return p(e,a)?(_(e,a),!0):!1},release(e){let t=r.get(e);if(t){if(f(e)===t.token)try{O(o(e))}catch{}v(e)}},releaseAll(){for(let e of[...r.keys()])x.release(e)},isOwner(e){if(i)return!1;let t=r.get(e);return t!=null&&f(e)===t.token},peekLockedByOther(e){if(i)return!1;let n=r.get(e);if(n!=null&&f(e)===n.token)return!1;let a;try{a=D(o(e)).mtimeMs}catch{return!1}return Date.now()-a<=t},inspect(e){let t=d(e);if(t===null)return{locked:!1};let n;try{n=Date.now()-D(o(e)).mtimeMs}catch{return{locked:!1}}let r=t.pid!==void 0&&t.host!==void 0&&t.host===a?u(t.pid):void 0;return{locked:!0,pid:t.pid,hostname:t.host,alive:r,mtimeAgoMs:n}},forceRelease(e){try{O(o(e))}catch{}v(e)},close(){i=!0,x.releaseAll()}};return e.installExitHook!==!1&&process.on(`exit`,()=>x.releaseAll()),x}function fe(){return{acquire:()=>!0,release:()=>{},releaseAll:()=>{},isOwner:()=>!0,peekLockedByOther:()=>!1,inspect:()=>({locked:!1}),forceRelease:()=>{},close:()=>{}}}const pe={warn:()=>{}};var me=class{repo;resolveWorkspaceKey;defaultPageSize;logger;persisted=new Map;maxLoadEntries;canStartHistory;writeLease;stripInactiveReplacements;constructor(e){this.repo=e.repo;let t=e.workspaceKey;this.resolveWorkspaceKey=typeof t==`function`?()=>t()||`default`:()=>t||`default`,this.defaultPageSize=e.defaultPageSize??20,this.logger=e.logger??pe,this.maxLoadEntries=e.maxLoadEntries,this.canStartHistory=e.canStartHistory,this.writeLease=e.writeLease,this.stripInactiveReplacements=e.stripInactiveReplacements??!1}assertWritable(e){if(this.writeLease&&!this.writeLease.acquire(e))throw this.logger.warn({sessionId:e},`archive/restore rejected: session write lease held by another live process (read-only; RFC-159 D3)`),new q(e)}async archiveSession(e){let t=this.repo;if(typeof t.archiveSession!=`function`)throw Error(`archiveSession is not supported by this repository`);return this.assertWritable(e),t.archiveSession(e)}async restoreArchivedSession(e){let t=this.repo;return typeof t.restoreArchivedSession==`function`?(this.assertWritable(e),t.restoreArchivedSession(e)):0}async save(e){if(this.writeLease&&!this.writeLease.acquire(e.id))throw this.logger.warn({sessionId:e.id},`save rejected: session write lease held by another live process (read-only; RFC-159 D3)`),new q(e.id);await this.repo.createSession(B(e,this.resolveWorkspaceKey()));let t=this.persisted.get(e.id),n=0;if(t!=null){let r=e.entries.findIndex(e=>e.id===t);n=r>=0?r+1:0}if(n===0){let n=await this.repo.getEntryCount(e.id);n>0&&t==null&&this.logger.warn({sessionId:e.id,dbCount:n},`Session has persisted entries but no local cursor (restart or concurrent writer); reconciling via full idempotent append (append-forever, no loss)`)}for(let t=n;t<e.entries.length;t++){let n=V(e.entries[t]),r=await R(n.type,n.data,this.repo);await this.repo.appendEntry(e.id,{...n,data:r})}let{leafPersisted:r}=await this.repo.touchSession(e.id,e.leafId,e.metadata.lastActiveAt,e.metadata.title,e.metadata.titleSource,e.metadata.config,e.metadata.archived,e.metadata.pinned,e.metadata.pinGroup);!r&&e.leafId!=null&&this.logger.warn({sessionId:e.id,rejectedLeafId:e.leafId},`touchSession: leafId not found among session entries (rejected to avoid dangling leaf; likely concurrent writer race); existing leaf_id preserved`);let i=e.entries[e.entries.length-1];i?this.persisted.set(e.id,i.id):this.persisted.delete(e.id)}async load(e){let t=await this.repo.getSession(e);if(!t)return null;let n=this.resolveWorkspaceKey(),r=t.workspaceKey||`default`;if(r!==n)return this.logger.warn({sessionId:e,sessionWorkspaceKey:r,expectedWorkspaceKey:n},`RelationalSessionPersistence.load: session belongs to a different workspace, refusing cross-workspace restore`),null;let i=await W(e,this.repo,{...this.maxLoadEntries==null?{}:{maxEntries:this.maxLoadEntries},...this.canStartHistory?{canStartHistory:this.canStartHistory}:{},...this.stripInactiveReplacements?{stripInactiveReplacements:!0}:{}}),a=i?.entries[i.entries.length-1];return a&&this.persisted.set(e,a.id),i}getPersistedCursor(e){return this.persisted.get(e)}async hydrateReplacements(e,t){return K(e,t,this.repo)}async delete(e){let t=await this.repo.deleteSession(e);return this.persisted.delete(e),this.writeLease?.release(e),t}async list(){return(await this.repo.listSessions(this.resolveWorkspaceKey())).map(e=>e.id)}async listRecentMeta(e){return this.repo.listRecentSessionIds(this.resolveWorkspaceKey(),e)}async listPaginated(e){let t=await this.repo.listSessions(this.resolveWorkspaceKey()),n=e.sortBy===`createdAt`?[...t].sort((e,t)=>t.createdAt-e.createdAt):t,r=e.order===`asc`?[...n].reverse():n,i=e.pageSize??this.defaultPageSize,a=r.length,o=Math.max(1,Math.ceil(a/i)),s=Math.max(0,Math.min(e.page,o-1));return{items:r.slice(s*i,s*i+i).map(e=>e.id),total:a,page:s,pageSize:i,totalPages:o,hasNext:s<o-1,hasPrevious:s>0}}};const Y=[{version:1,up:e=>{e.exec(`
|
|
1
|
+
import{DiskPersistence as e,MemoryPersistenceBase as t,RemotePersistence as n,RemotePersistenceError as r,RemoteSnapshotConflictError as i,acquireDb as a,paginate as o,releaseDb as s}from"@x-otto/persistence";import{currentHostname as c,decodeLeaseToken as l,encodeLeaseToken as u,isProcessAlive as d,normalizeEnv as f}from"@x-otto/env";import{readFile as p,readdir as m,stat as h}from"node:fs/promises";import{dirname as g,join as _,resolve as v}from"node:path";import{createHash as y,randomUUID as b}from"node:crypto";import{closeSync as ee,createWriteStream as x,existsSync as S,mkdirSync as C,openSync as w,readFileSync as T,renameSync as te,rmSync as ne,statSync as E,unlinkSync as D,utimesSync as O,writeSync as k}from"node:fs";import{createGzip as A,gunzipSync as j}from"node:zlib";const M={derived:0,ai:1,custom:2};function N(e){if(typeof e!=`object`||!e)return 0;let t=e,n=0,r=t.tool_calls;if(Array.isArray(r))for(let e of r){if(typeof e!=`object`||!e)continue;let t=e.function;t&&typeof t==`object`&&typeof t.arguments==`string`&&(n+=t.arguments.length)}let i=t.content;if(typeof i==`string`)return n+i.length;if(!Array.isArray(i))return n;for(let e of i){if(typeof e!=`object`||!e)continue;let t=e;typeof t.text==`string`&&(n+=t.text.length);let r=t.source;r&&typeof r==`object`&&typeof r.data==`string`&&(n+=r.data.length),typeof t.data==`string`&&(n+=t.data.length);let i=t.image_url;i&&typeof i==`object`&&typeof i.url==`string`&&(n+=i.url.length),t.type===`tool_call`&&typeof t.arguments==`object`&&t.arguments!=null&&(n+=JSON.stringify(t.arguments).length),t.type===`tool_use`&&t.input!=null&&(n+=JSON.stringify(t.input).length)}return n}var P=class{sessionEntries=[];entryMap=new Map;_estimatedContentBytes=0;get estimatedContentBytes(){return this._estimatedContentBytes}get messageCount(){return this.meta.messageCount}verifyEstimatedContentBytes(){let e=0;for(let t of this.sessionEntries)if(t.type===`message`)e+=N(t.message);else if(t.type===`compaction`&&t.replacement)for(let n of t.replacement)e+=N(n);return{counter:this._estimatedContentBytes,recomputed:e,drift:e-this._estimatedContentBytes}}meta;panelState={};constructor(e,t,n){this.id=e;let r=Date.now();this.meta={createdAt:r,lastActiveAt:r,messageCount:0,compactionCount:0,parentSessionId:t,forkPoint:n,tags:[]}}_leafId=void 0;get leafId(){return this._leafId}markActivity(){this.meta.lastActiveAt=Date.now()}append(e){let t={type:`message`,id:crypto.randomUUID(),parentId:this._leafId,message:e,timestamp:Date.now()};this._leafId=t.id,this.sessionEntries.push(t),this.entryMap.set(t.id,t),this.meta.messageCount++,this.markActivity(),this._estimatedContentBytes+=N(e)}removeLast(){if(!this._leafId)return;let e=this.entryMap.get(this._leafId);if(!e||e.type!==`message`)return;let t=this.sessionEntries.lastIndexOf(e);t!==-1&&(this.sessionEntries.splice(t,1),this.entryMap.delete(e.id),this._leafId=e.parentId,this.meta.messageCount=Math.max(0,this.meta.messageCount-1),this._estimatedContentBytes-=N(e.message))}compact(e,t){let n=this.getBranchMessageEntries();if(t<=0||t>n.length)return;let r={type:`compaction`,id:crypto.randomUUID(),parentId:this._leafId,summary:e,compactedCount:t,timestamp:Date.now()};this.sessionEntries.push(r),this.entryMap.set(r.id,r),this.meta.compactionCount++,this.markActivity(),this._leafId=r.id}recordCompaction(e,t){let n=this.findActiveCompaction(),r={type:`compaction`,id:crypto.randomUUID(),parentId:this._leafId,summary:e,compactedCount:t.length,replacement:[...t],timestamp:Date.now()};for(let e of t)this._estimatedContentBytes+=N(e);this.sessionEntries.push(r),this.entryMap.set(r.id,r),this.meta.compactionCount++,this.markActivity(),this._leafId=r.id,n&&n.replacement!=null&&this.replacementStripEligibility?.(n.id)===!0&&this.stripReplacementInPlace(n.id)}replacementStripEligibility;setReplacementStripEligibility(e){this.replacementStripEligibility=e}findActiveCompaction(){return this._leafId?this.findActiveCompactionFrom(this._leafId):void 0}stripReplacementInPlace(e){let t=this.entryMap.get(e);if(!t||t.type!==`compaction`)return;let n=t;if(n.replacement==null)return;for(let e of n.replacement)this._estimatedContentBytes-=N(e);this._estimatedContentBytes<0&&(this._estimatedContentBytes=0);let{replacement:r,...i}=n,a={...i,replacementStripped:!0};this.entryMap.set(e,a);let o=this.sessionEntries.findIndex(t=>t.id===e);o>=0&&(this.sessionEntries[o]=a)}clearContext(e){let t={type:`clear`,id:crypto.randomUUID(),parentId:this._leafId,timestamp:Date.now()};this.sessionEntries.push(t),this.entryMap.set(t.id,t),this.markActivity(),this._leafId=t.id,e?.purge===!0&&this.purgeBeforeBoundary(t.id)}purgeClearedHistory(){let e;for(let t=this.sessionEntries.length-1;t>=0;t--)if(this.sessionEntries[t].type===`clear`){e=this.sessionEntries[t].id;break}return e?this.purgeBeforeBoundary(e):{removedCount:0,strippedReplacements:0}}purgeBeforeBoundary(e){let t=this.sessionEntries.findIndex(t=>t.id===e);if(t<0)return{removedCount:0,strippedReplacements:0};let n=0,r=0,i=0,a=t;for(;r<a;){let e=this.sessionEntries[r];e.type===`message`?(this._estimatedContentBytes-=N(e.message),this.entryMap.delete(e.id),this.sessionEntries.splice(r,1),a--,i++):(e.type===`compaction`&&e.replacement!=null&&(this.stripReplacementInPlace(e.id),n++),r++)}return this._estimatedContentBytes<0&&(this._estimatedContentBytes=0),this.meta.messageCount-=i,{removedCount:i,strippedReplacements:n}}branch(e){if(!this.entryMap.has(e))throw Error(`Entry "${e}" not found in session "${this.id}"`);let t=this.findActiveCompactionFrom(e);if(t&&t.replacementStripped)throw Error(`branch: target chain's active compaction boundary "${t.id}" has a stripped replacement (RFC-160); hydrate it via loadEntriesByIds before branching`);this._leafId=e,this.markActivity()}findActiveCompactionFrom(e){let t=new Set,n=this.entryMap.get(e);for(;n&&!t.has(n.id);){if(t.add(n.id),n.type===`compaction`)return n;if(n.type===`clear`)return;n=n.parentId?this.entryMap.get(n.parentId):void 0}}entries(){return this.sessionEntries}branchEntries(){return this.walkBranch()}buildContext(){let e=this.walkBranch(),t=this.lastBoundaryIndex(e),n=e.slice(t+1).filter(e=>e.type===`message`).map(e=>e.message);if(t===-1)return{messages:n};let r=e[t];if(r.type===`clear`)return{messages:n};let i=r;return{summary:i.summary,messages:i.replacement?[...i.replacement,...n]:n}}messages(){return this.walkBranch().filter(e=>e.type===`message`).map(e=>e.message)}visibleMessages(){let e=this.walkBranch(),t=-1;for(let n=e.length-1;n>=0;n--)if(e[n]?.type===`clear`){t=n;break}return e.slice(t+1).filter(e=>e.type===`message`).map(e=>e.message)}metadata(){return{...this.meta,tags:[...this.meta.tags],...this.meta.config?{config:structuredClone(this.meta.config)}:{}}}setTitle(e,t){let n=this.meta.titleSource==null?-1:M[this.meta.titleSource];return M[t]<n?!1:(this.meta.title=e,this.meta.titleSource=t,!0)}setSdkVersion(e){this.meta.sdkVersion=e}setArchived(e){this.meta.archived=e}setPinned(e,t){this.meta.pinned=e,this.meta.pinGroup=e?t:void 0}touchIfActivity(e){e?.touch!==!1&&this.markActivity()}getTodoList(){return this.panelState.todoList}setTodoList(e,t){this.panelState.todoList=[...e],this.touchIfActivity(t)}getEditedFiles(){return this.panelState.editedFiles}setEditedFiles(e,t){this.panelState.editedFiles=e.slice(0,50),this.touchIfActivity(t)}getInputHistory(){return this.meta.config?.inputHistory}setInputHistory(e){if(e.length===0){this.meta.config?.inputHistory!==void 0&&delete this.meta.config.inputHistory;return}this.meta.config||(this.meta.config={}),this.meta.config.inputHistory=e.slice(-100)}getSubagents(){return this.panelState.subagents}setSubagents(e,t){this.panelState.subagents=e.slice(0,100),this.touchIfActivity(t)}getTurnSummaries(){return this.panelState.turnSummaries}setTurnSummaries(e,t){this.panelState.turnSummaries=e.slice(-200),this.touchIfActivity(t)}getTurnCount(){return this.meta.config?.turnCount}setTurnCount(e){this.meta.config||(this.meta.config={}),this.meta.config.turnCount=e}getDrafts(){return this.panelState.drafts}setDrafts(e,t){this.panelState.drafts=e.slice(0,50),this.touchIfActivity(t)}capStoredHistory(e,t){let n=0;for(let e of this.sessionEntries)e.type===`message`&&n++;if(n<=e)return{capped:!1,removedCount:0,boundaryLimited:!1,activeOversized:!1};let r=n-e,{removed:i,boundaryLimited:a}=this.removeOldestMessages(r,t);return this.meta.messageCount=n-i,{capped:i>0,removedCount:i,boundaryLimited:a,activeOversized:this.meta.messageCount>e}}wouldTrimTouchActiveContext(e){let t=this.meta.messageCount;if(t<=e)return!1;let n=t-e,r=this.findActiveCompaction()?.id;if(r===void 0)return!0;let i=0;for(let e of this.sessionEntries){if(e.id===r)break;e.type===`message`&&i++}return i<n}wouldByteTrimTouchActiveContext(e){if(e<=0||this._estimatedContentBytes<=e)return!1;let t=this.findActiveCompaction()?.id;if(t===void 0)return!0;let n=0;for(let e of this.sessionEntries){if(e.id===t)break;e.type===`message`&&(n+=N(e.message))}return this._estimatedContentBytes-n>e}capStoredHistoryByBytes(e,t){if(e<=0||this._estimatedContentBytes<=e)return{capped:!1,removedCount:0,boundaryLimited:!1,activeOversized:!1};let n=0;for(let e of this.sessionEntries)e.type===`message`&&n++;let r=this._estimatedContentBytes,i=0;for(let t of this.sessionEntries){if(r<=e||i>=n-1)break;t.type===`message`&&(r-=N(t.message),i++)}if(i===0)return{capped:!1,removedCount:0,boundaryLimited:!1,activeOversized:!1};let{removed:a,boundaryLimited:o}=this.removeOldestMessages(i,t);return this.meta.messageCount=n-a,{capped:a>0,removedCount:a,boundaryLimited:o,activeOversized:this._estimatedContentBytes>e}}removeOldestMessages(e,t){let n=this.findActiveCompaction()?.id,r=!1,i=0,a=0;for(;a<this.sessionEntries.length&&i<e;){let e=this.sessionEntries[a];if(n!==void 0&&e.id===n){r=!0;break}e.type===`message`?(this._estimatedContentBytes-=N(e.message),this.entryMap.delete(e.id),this.sessionEntries.splice(a,1),i++):a++}if(t)for(;a<this.sessionEntries.length;){let e=this.sessionEntries[a];if(n!==void 0&&e.id===n){r=!0;break}if(e.type!==`message`){a++;continue}if(t(e.message))break;this._estimatedContentBytes-=N(e.message),this.entryMap.delete(e.id),this.sessionEntries.splice(a,1),i++}return this._estimatedContentBytes<0&&(this._estimatedContentBytes=0),{removed:i,boundaryLimited:r}}setTags(e){this.meta.tags=[...e]}addTag(e){this.meta.tags.includes(e)||this.meta.tags.push(e)}restoreEntries(e,t,n){this.sessionEntries.length=0,this.entryMap.clear();let r=0;for(let t of e)if(this.sessionEntries.push(t),this.entryMap.set(t.id,t),t.type===`message`)r+=N(t.message);else if(t.type===`compaction`&&t.replacement)for(let e of t.replacement)r+=N(e);this._estimatedContentBytes=r,Object.assign(this.meta,t),this._leafId=n&&this.entryMap.has(n)?n:e.length>0?e[e.length-1]?.id:void 0}toSnapshot(){return{entries:[...this.sessionEntries],metadata:this.metadata(),leafId:this._leafId}}walkBranch(){if(!this._leafId)return[];let e=[],t=new Set,n=this.entryMap.get(this._leafId);for(;n&&!t.has(n.id);)t.add(n.id),e.push(n),n=n.parentId?this.entryMap.get(n.parentId):void 0;return e.reverse(),e}getBranchMessageEntries(){let e=this.walkBranch(),t=this.lastBoundaryIndex(e);return e.slice(t+1).filter(e=>e.type===`message`)}lastBoundaryIndex(e){for(let t=e.length-1;t>=0;t--){let n=e[t]?.type;if(n===`compaction`||n===`clear`)return t}return-1}},F=class{sessions=new Map;async createSession(e=crypto.randomUUID()){let t=new P(e);return this.sessions.set(e,t),t}getSession(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values())}listSessionsPaginated(e){let{page:t,sortBy:n=`lastActiveAt`,order:r=`desc`}=e,i=e.pageSize??50,a=Array.from(this.sessions.values());return a.sort((e,t)=>{let i=e.metadata(),a=t.metadata(),o=n===`createdAt`?i.createdAt:i.lastActiveAt,s=n===`createdAt`?a.createdAt:a.lastActiveAt;return r===`asc`?o-s:s-o}),o(a,{page:t,pageSize:i})}async deleteSession(e){return this.sessions.delete(e)}async forkSession(e,t=crypto.randomUUID()){let n=this.sessions.get(e);if(!n)return;let r=n.toSnapshot(),i=new P(t,e,r.entries.length);return i.restoreEntries([...r.entries],{...r.metadata,createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:e,forkPoint:r.entries.length,tags:[...r.metadata.tags,`fork`]},r.leafId),this.sessions.set(t,i),i}};function re(){return new F}const ie=f(process.env.OTTO_SESSION_IDLE_TIMEOUT_MS,1800*1e3),ae=f(process.env.OTTO_SESSION_MAX,50),I=f(process.env.OTTO_SESSION_PAGE_SIZE,20),oe=f(process.env.OTTO_SESSION_SNAPSHOT_VERSION,1);var se=class extends t{constructor(){super({defaultPageSize:I,defaultSortBy:`lastActiveAt`})}extractId(e){return e.id}getSortValue(e,t){return t===`createdAt`?e.metadata.createdAt:e.metadata.lastActiveAt}async listRecentMeta(e){return this.entries().filter(([,e])=>!e.metadata.archived).sort(([,e],[,t])=>t.metadata.lastActiveAt-e.metadata.lastActiveAt).slice(0,e).map(([e])=>e)}},ce=class extends e{turnFlush=`snapshot`;sessionBaseDir;sessionExtension=`.session.json`;constructor(e){super({baseDir:e.baseDir,extension:`.session.json`,defaultPageSize:I}),this.sessionBaseDir=e.baseDir}extractId(e){return e.id}async listRecentMeta(e){let t;try{t=await m(this.sessionBaseDir)}catch{return[]}let n=t.filter(e=>e.endsWith(this.sessionExtension)),r=await Promise.all(n.map(async e=>{let t=await h(_(this.sessionBaseDir,e)).catch(()=>null);return{id:decodeURIComponent(e.slice(0,-this.sessionExtension.length)),mtime:t?.mtimeMs??0}}));r.sort((e,t)=>t.mtime-e.mtime);let i=[];for(let{id:t}of r){if(i.length>=e)break;let n=await this.load(t).catch(()=>null);n&&(n.metadata.archived||i.push(t))}return i}};function L(e){return`sha256:${y(`sha256`).update(e,`utf-8`).digest(`hex`)}`}async function R(e,t,n){if(e!==`compaction`)return t;let r=t.replacement;if(!Array.isArray(r))return t;let i=r.map(e=>JSON.stringify(e)),a=i.map(L);await n.putBlobs(i.map((e,t)=>({hash:a[t],content:e})));let{replacement:o,...s}=t;return{...s,replacementHashes:a}}async function z(e,t,n){if(e!==`compaction`)return t;let r=t.replacementHashes;if(!Array.isArray(r)||r.length===0){if(Array.isArray(r)){let{replacementHashes:e,...n}=t;return{...n,replacement:[]}}return t}let i=await n.getBlobs(r),a=r.map(e=>{let t=i.get(e);if(t==null)throw Error(`decodeReplacementFromBlobs: blob ${e} missing from message_blobs (corrupted import/partial backup?); refusing to assemble a lossy replacement (RFC-160 D7)`);return JSON.parse(t)}),{replacementHashes:o,...s}=t;return{...s,replacement:a}}function B(e,t){let n=e.metadata;return{id:e.id,workspaceKey:t,...n.title==null?{}:{title:n.title},...n.titleSource==null?{}:{titleSource:n.titleSource},...n.parentSessionId==null?{}:{parentSessionId:n.parentSessionId},...n.forkPoint==null?{}:{forkPoint:n.forkPoint},...e.leafId==null?{}:{leafId:e.leafId},tags:n.tags??[],...n.config==null?{}:{config:n.config},createdAt:n.createdAt,lastActiveAt:n.lastActiveAt,...n.archived==null?{}:{archived:n.archived},...n.pinned==null?{}:{pinned:n.pinned},...n.pinGroup==null?{}:{pinGroup:n.pinGroup}}}function V(e){let{type:t,id:n,parentId:r,timestamp:i,...a}=e;return{entryId:n,...r==null?{}:{parentId:r},type:t,data:a,createdAt:i}}function H(e){return{type:e.type,id:e.entryId,...e.parentId==null?{}:{parentId:e.parentId},timestamp:e.createdAt,...e.data}}async function U(e,t,n){await n.createSession(B(e,t));for(let t of e.entries)await n.appendEntry(e.id,V(t));await n.touchSession(e.id,e.leafId,e.metadata.lastActiveAt,e.metadata.title,e.metadata.titleSource,e.metadata.config,e.metadata.archived,e.metadata.pinned,e.metadata.pinGroup)}async function W(e,t,n){let r=await t.getSession(e);if(!r)return null;let i,a=!1;n?.maxEntries==null?i=(await t.loadEntries(e)).map(e=>H(e)):await t.getEntryCount(e)>n.maxEntries?(i=(await t.loadTailEntries(e,n.maxEntries)).map(e=>H(e)),a=!0,n.canStartHistory&&(i=ue(i,n.canStartHistory))):i=(await t.loadEntries(e)).map(e=>H(e)),n?.stripInactiveReplacements?(i=le(i,r.leafId??void 0),i=await G(i,t,{onlyUnstripped:!0})):i=await G(i,t,{onlyUnstripped:!1});let o=a?await t.countEntriesByType(e,`message`):i.filter(e=>e.type===`message`).length,s=a?await t.countEntriesByType(e,`compaction`):i.filter(e=>e.type===`compaction`).length,c={createdAt:r.createdAt,lastActiveAt:r.lastActiveAt,messageCount:o,compactionCount:s,tags:r.tags,...r.title==null?{}:{title:r.title},...r.titleSource==null?{}:{titleSource:r.titleSource},...r.parentSessionId==null?{}:{parentSessionId:r.parentSessionId},...r.forkPoint==null?{}:{forkPoint:r.forkPoint},...r.config==null?{}:{config:r.config},...r.archived==null?{}:{archived:r.archived},...r.pinned==null?{}:{pinned:r.pinned},...r.pinGroup==null?{}:{pinGroup:r.pinGroup}};return{version:1,id:e,entries:i,metadata:c,...r.leafId==null?{}:{leafId:r.leafId}}}async function G(e,t,n){let r=[];for(let i of e){let e=i;if(e.type!==`compaction`||e.replacementHashes==null){r.push(i);continue}if(n.onlyUnstripped&&e.replacementStripped){let{replacementHashes:t,...n}=e;r.push(n);continue}let{replacementStripped:a,...o}=await z(`compaction`,e,t);r.push(o)}return r}function le(e,t){let n=new Map;for(let t of e)n.set(t.id,t);let r,i=new Set,a=t?n.get(t):void 0;for(;a&&!i.has(a.id);){if(i.add(a.id),a.type===`compaction`){r=a.id;break}if(a.type===`clear`)break;a=a.parentId?n.get(a.parentId):void 0}let o=-1;for(let t=e.length-1;t>=0;t--)if(e[t].type===`compaction`){o=t;break}return e.map((e,t)=>{if(e.type!==`compaction`||e.id===r||t===o)return e;let n=e;if(n.replacement!=null){let{replacement:e,...t}=n;return{...t,replacementStripped:!0}}return n.replacementHashes==null?e:{...n,replacementStripped:!0}})}function ue(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r.type!==`message`||t(r.message))break;n++}return n>0?e.slice(n):e}function de(e){return typeof e?.hydrateReplacements==`function`}function fe(e){return e.some(e=>e.type===`compaction`&&e.replacementStripped)}async function K(e,t,n){let r=t.filter(e=>e.type===`compaction`&&e.replacementStripped).map(e=>e.id);if(r.length===0)return[...t];let i=await n.loadEntriesByIds(e,r),a=new Map;for(let e of i)a.set(e.entryId,e.data);let o=[];for(let r of t){if(r.type!==`compaction`||!r.replacementStripped){o.push(r);continue}let t=a.get(r.id);if(t&&t.replacementHashes!=null&&(t=await z(`compaction`,t,n)),!t||t.replacement==null)throw Error(`hydrateStrippedReplacements: authoritative row for compaction "${r.id}" in session "${e}" is missing or has no replacement (corrupted import?); refusing to continue with stripped state (RFC-160 rule 3)`);let{replacementStripped:i,...s}=r;o.push({...s,replacement:t.replacement})}return o}var q=class extends Error{constructor(e){super(`Session write lease denied for ${e}: another live process owns the write lease (this process is read-only for the session; refusing to save — RFC-159 D3)`),this.sessionId=e,this.name=`SessionWriteLeaseDeniedError`}};function pe(e){let t=e.staleMs??6e4,n=e.renewEveryMs??1e4,r=new Map,i=!1,a=c(),o=t=>_(e.lockDir,`${t}.lock`),s=e=>{try{return l(T(o(e),`utf-8`).trim())}catch{return null}},f=e=>s(e)?.token??null,p=(t,n)=>{try{C(e.lockDir,{recursive:!0});let r=w(o(t),`wx`);try{k(r,u(n,process.pid,a))}finally{ee(r)}return!0}catch(e){if(e.code!==`EEXIST`)throw e;return!1}},m=e=>e.pid===void 0||e.host===void 0||e.host!==a?!1:!d(e.pid),h=e=>e.pid===void 0||e.host===void 0||e.host!==a?!1:d(e.pid),g=(e,t)=>{let i=setInterval(()=>{if(f(e)!==t){v(e);return}try{let t=new Date;O(o(e),t,t)}catch{v(e)}},n);i.unref(),r.set(e,{token:t,timer:i})},v=e=>{let t=r.get(e);t&&(clearInterval(t.timer),r.delete(e))},y={acquire(e){if(i)return!1;let n=r.get(e);if(n){if(f(e)===n.token)return!0;v(e)}let a=b();if(p(e,a))return g(e,a),!0;let c=s(e),l;try{l=E(o(e)).mtimeMs}catch{return p(e,a)?(g(e,a),!0):!1}if(c!==null&&h(c)||!(c!==null&&m(c))&&Date.now()-l<=t)return!1;let u=`${o(e)}.stale-${b()}`;try{te(o(e),u),ne(u,{force:!0})}catch{return!1}return p(e,a)?(g(e,a),!0):!1},release(e){let t=r.get(e);if(t){if(f(e)===t.token)try{D(o(e))}catch{}v(e)}},releaseAll(){for(let e of[...r.keys()])y.release(e)},isOwner(e){if(i)return!1;let t=r.get(e);return t!=null&&f(e)===t.token},peekLockedByOther(e){if(i)return!1;let n=r.get(e);if(n!=null&&f(e)===n.token)return!1;let a;try{a=E(o(e)).mtimeMs}catch{return!1}return Date.now()-a<=t},inspect(e){let t=s(e);if(t===null)return{locked:!1};let n;try{n=Date.now()-E(o(e)).mtimeMs}catch{return{locked:!1}}let r=t.pid!==void 0&&t.host!==void 0&&t.host===a?d(t.pid):void 0;return{locked:!0,pid:t.pid,hostname:t.host,alive:r,mtimeAgoMs:n}},forceRelease(e){try{D(o(e))}catch{}v(e)},close(){i=!0,y.releaseAll()}};return e.installExitHook!==!1&&process.on(`exit`,()=>y.releaseAll()),y}function me(){return{acquire:()=>!0,release:()=>{},releaseAll:()=>{},isOwner:()=>!0,peekLockedByOther:()=>!1,inspect:()=>({locked:!1}),forceRelease:()=>{},close:()=>{}}}const he={warn:()=>{}};var ge=class{repo;resolveWorkspaceKey;defaultPageSize;logger;persisted=new Map;maxLoadEntries;canStartHistory;writeLease;stripInactiveReplacements;constructor(e){this.repo=e.repo;let t=e.workspaceKey;this.resolveWorkspaceKey=typeof t==`function`?()=>t()||`default`:()=>t||`default`,this.defaultPageSize=e.defaultPageSize??20,this.logger=e.logger??he,this.maxLoadEntries=e.maxLoadEntries,this.canStartHistory=e.canStartHistory,this.writeLease=e.writeLease,this.stripInactiveReplacements=e.stripInactiveReplacements??!1}assertWritable(e){if(this.writeLease&&!this.writeLease.acquire(e))throw this.logger.warn({sessionId:e},`archive/restore rejected: session write lease held by another live process (read-only; RFC-159 D3)`),new q(e)}async archiveSession(e){let t=this.repo;if(typeof t.archiveSession!=`function`)throw Error(`archiveSession is not supported by this repository`);return this.assertWritable(e),t.archiveSession(e)}async restoreArchivedSession(e){let t=this.repo;return typeof t.restoreArchivedSession==`function`?(this.assertWritable(e),t.restoreArchivedSession(e)):0}async save(e){if(this.writeLease&&!this.writeLease.acquire(e.id))throw this.logger.warn({sessionId:e.id},`save rejected: session write lease held by another live process (read-only; RFC-159 D3)`),new q(e.id);await this.repo.createSession(B(e,this.resolveWorkspaceKey()));let t=this.persisted.get(e.id),n=0;if(t!=null){let r=e.entries.findIndex(e=>e.id===t);n=r>=0?r+1:0}if(n===0){let n=await this.repo.getEntryCount(e.id);n>0&&t==null&&this.logger.warn({sessionId:e.id,dbCount:n},`Session has persisted entries but no local cursor (restart or concurrent writer); reconciling via full idempotent append (append-forever, no loss)`)}for(let t=n;t<e.entries.length;t++){let n=V(e.entries[t]),r=await R(n.type,n.data,this.repo);await this.repo.appendEntry(e.id,{...n,data:r})}let{leafPersisted:r}=await this.repo.touchSession(e.id,e.leafId,e.metadata.lastActiveAt,e.metadata.title,e.metadata.titleSource,e.metadata.config,e.metadata.archived,e.metadata.pinned,e.metadata.pinGroup);!r&&e.leafId!=null&&this.logger.warn({sessionId:e.id,rejectedLeafId:e.leafId},`touchSession: leafId not found among session entries (rejected to avoid dangling leaf; likely concurrent writer race); existing leaf_id preserved`);let i=e.entries[e.entries.length-1];i?this.persisted.set(e.id,i.id):this.persisted.delete(e.id)}async load(e){let t=await this.repo.getSession(e);if(!t)return null;let n=this.resolveWorkspaceKey(),r=t.workspaceKey||`default`;if(r!==n)return this.logger.warn({sessionId:e,sessionWorkspaceKey:r,expectedWorkspaceKey:n},`RelationalSessionPersistence.load: session belongs to a different workspace, refusing cross-workspace restore`),null;let i=await W(e,this.repo,{...this.maxLoadEntries==null?{}:{maxEntries:this.maxLoadEntries},...this.canStartHistory?{canStartHistory:this.canStartHistory}:{},...this.stripInactiveReplacements?{stripInactiveReplacements:!0}:{}}),a=i?.entries[i.entries.length-1];return a&&this.persisted.set(e,a.id),i}getPersistedCursor(e){return this.persisted.get(e)}async hydrateReplacements(e,t){return K(e,t,this.repo)}async delete(e){let t=await this.repo.deleteSession(e);return this.persisted.delete(e),this.writeLease?.release(e),t}async list(){return(await this.repo.listSessions(this.resolveWorkspaceKey())).map(e=>e.id)}async listRecentMeta(e){return this.repo.listRecentSessionIds(this.resolveWorkspaceKey(),e)}async listPaginated(e){let t=await this.repo.listSessions(this.resolveWorkspaceKey()),n=e.sortBy===`createdAt`?[...t].sort((e,t)=>t.createdAt-e.createdAt):t,r=e.order===`asc`?[...n].reverse():n,i=e.pageSize??this.defaultPageSize;return o(r.map(e=>e.id),{page:e.page,pageSize:i})}};const J=[{version:1,up:e=>{e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS workspaces (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
name TEXT NOT NULL,
|
|
@@ -45,15 +45,15 @@ import{DiskPersistence as e,MemoryPersistenceBase as t,RemotePersistence as n,Re
|
|
|
45
45
|
content TEXT NOT NULL,
|
|
46
46
|
created_at INTEGER NOT NULL
|
|
47
47
|
);
|
|
48
|
-
`)}}],
|
|
49
|
-
`));return r.end(),await new Promise((e,t)=>{i.on(`finish`,e),i.on(`error`,t)}),this.db.prepare(`UPDATE sessions SET archived = 1 WHERE id = ?`).run(e),t}async restoreArchivedSession(e){let t=
|
|
48
|
+
`)}}],Y=`default`;var X=class{db;archiveDir;ephemeral;constructor(e){this.db=a(e.dbPath,e.wal!==!1,J),this.ephemeral=e.dbPath===`:memory:`,this.archiveDir=v(g(e.dbPath),`archives`)}close(){s(this.db)}async archiveSession(e){if(this.ephemeral)return this.db.prepare(`UPDATE sessions SET archived = 1 WHERE id = ?`).run(e),`:memory:/${e}.jsonl.gz`;let t=v(this.archiveDir,`${e}.jsonl.gz`);S(this.archiveDir)||C(this.archiveDir,{recursive:!0});let n=await this.loadEntries(e),r=A(),i=x(t);r.pipe(i);let a=new TextEncoder;for(let e of n)r.write(a.encode(JSON.stringify(e)+`
|
|
49
|
+
`));return r.end(),await new Promise((e,t)=>{i.on(`finish`,e),i.on(`error`,t)}),this.db.prepare(`UPDATE sessions SET archived = 1 WHERE id = ?`).run(e),t}async restoreArchivedSession(e){let t=v(this.archiveDir,`${e}.jsonl.gz`);if(!S(t))return 0;let n=j(await p(t)).toString(`utf-8`).trim().split(`
|
|
50
50
|
`).filter(Boolean),r=await this.loadEntries(e),i=0;for(let t of n){let n=JSON.parse(t);r.some(e=>e.entryId===n.entryId)||(await this.appendEntry(e,n),i++)}return this.db.prepare(`UPDATE sessions SET archived = 0 WHERE id = ?`).run(e),i}async upsertWorkspace(e){this.db.prepare(`INSERT INTO workspaces (id, name, owner_id, org_id, created_at)
|
|
51
51
|
VALUES (?, ?, ?, ?, ?)
|
|
52
52
|
ON CONFLICT (id) DO UPDATE SET
|
|
53
53
|
name = excluded.name, owner_id = excluded.owner_id, org_id = excluded.org_id`).run(e.id,e.name,e.ownerId??null,e.orgId??null,e.createdAt)}async getWorkspace(e){let t=this.db.prepare(`SELECT id, name, owner_id, org_id, created_at FROM workspaces WHERE id = ?`).get(e);return t?Z(t):null}async listWorkspaces(){return this.db.prepare(`SELECT id, name, owner_id, org_id, created_at FROM workspaces ORDER BY created_at DESC`).all().map(Z)}async createSession(e){this.db.prepare(`INSERT INTO sessions
|
|
54
54
|
(id, workspace_key, title, title_source, parent_session_id, fork_point, leaf_id, owner_id, tags, config, next_seq, created_at, last_active_at, archived, pinned, pin_group)
|
|
55
55
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)
|
|
56
|
-
ON CONFLICT (id) DO NOTHING`).run(e.id,e.workspaceKey||
|
|
56
|
+
ON CONFLICT (id) DO NOTHING`).run(e.id,e.workspaceKey||Y,e.title??null,e.titleSource??null,e.parentSessionId??null,e.forkPoint??null,e.leafId??null,e.ownerId??null,JSON.stringify(e.tags??[]),e.config==null?null:JSON.stringify(e.config),e.createdAt,e.lastActiveAt,e.archived==null?null:e.archived?1:0,e.pinned==null?null:e.pinned?1:0,e.pinGroup??null)}async touchSession(e,t,n,r,i,a,o,s,c){return{leafPersisted:this.db.transaction(()=>{let l=null,u=!0;return t!=null&&(this.db.prepare(`SELECT 1 FROM session_entries WHERE session_id = ? AND entry_id = ?`).get(e,t)?l=t:u=!1),this.db.prepare(u?`UPDATE sessions SET
|
|
57
57
|
leaf_id = ?,
|
|
58
58
|
last_active_at = ?,
|
|
59
59
|
title = COALESCE(?, title),
|
|
@@ -71,18 +71,18 @@ import{DiskPersistence as e,MemoryPersistenceBase as t,RemotePersistence as n,Re
|
|
|
71
71
|
pinned = COALESCE(?, pinned),
|
|
72
72
|
pin_group = COALESCE(?, pin_group)
|
|
73
73
|
WHERE id = ?`).run(...u?[l]:[],n,r??null,i??null,a==null?null:JSON.stringify(a),o==null?null:o?1:0,s==null?null:s?1:0,c??null,e),u}).immediate()}}async getSession(e){let t=this.db.prepare(`SELECT * FROM sessions WHERE id = ?`).get(e);return t?Q(t):null}async listSessions(e){return this.db.prepare(`SELECT * FROM sessions
|
|
74
|
-
WHERE COALESCE(workspace_key, '${
|
|
75
|
-
ORDER BY last_active_at DESC`).all(e||
|
|
76
|
-
WHERE COALESCE(workspace_key, '${
|
|
74
|
+
WHERE COALESCE(workspace_key, '${Y}') = ?
|
|
75
|
+
ORDER BY last_active_at DESC`).all(e||Y).map(Q)}async listAllSessionIds(){return this.db.prepare(`SELECT id FROM sessions`).all().map(e=>e.id)}async listRecentSessionIds(e,t){return this.db.prepare(`SELECT id FROM sessions
|
|
76
|
+
WHERE COALESCE(workspace_key, '${Y}') = ?
|
|
77
77
|
AND COALESCE(archived, 0) = 0
|
|
78
78
|
AND next_seq > 0
|
|
79
79
|
ORDER BY last_active_at DESC
|
|
80
|
-
LIMIT ?`).all(e||
|
|
80
|
+
LIMIT ?`).all(e||Y,t).map(e=>e.id)}async deleteSession(e){return this.db.transaction(e=>(this.db.prepare(`DELETE FROM session_entries WHERE session_id = ?`).run(e),this.db.prepare(`DELETE FROM sessions WHERE id = ?`).run(e).changes>0)).immediate(e)}async appendEntry(e,t){return this.db.transaction((e,t)=>{let n=this.db.prepare(`SELECT seq FROM session_entries WHERE session_id = ? AND entry_id = ?`).get(e,t.entryId);if(n)return n.seq;let r=this.db.prepare(`SELECT next_seq FROM sessions WHERE id = ?`).get(e);if(!r)throw Error(`appendEntry: unknown session ${e}`);let i=r.next_seq;if(t.data.replacementStripped)throw Error(`appendEntry: refusing to persist stripped compaction entry ${t.entryId} as a new authoritative row for session ${e} (RFC-160 D1; hydrate before persisting)`);let a=this.db.prepare(`SELECT MAX(seq) AS max_seq FROM session_entries WHERE session_id = ?`).get(e);if(a.max_seq!=null&&i<=a.max_seq)throw Error(`appendEntry: next_seq invariant violated for session ${e} (next_seq=${i} <= MAX(seq)=${a.max_seq}); refusing to write (RFC-159 D5)`);return this.db.prepare(`INSERT INTO session_entries (session_id, seq, entry_id, parent_id, type, data, created_at)
|
|
81
81
|
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(e,i,t.entryId,t.parentId??null,t.type,JSON.stringify(t.data),t.createdAt),this.db.prepare(`UPDATE sessions SET next_seq = ?, last_active_at = ? WHERE id = ?`).run(i+1,t.createdAt,e),i}).immediate(e,t)}async loadEntries(e,t){return(t==null?this.db.prepare(`SELECT * FROM session_entries WHERE session_id = ? ORDER BY seq ASC`).all(e):this.db.prepare(`SELECT * FROM session_entries WHERE session_id = ? AND seq > ? ORDER BY seq ASC`).all(e,t)).map($)}async getEntryCount(e){return this.db.prepare(`SELECT next_seq FROM sessions WHERE id = ?`).get(e)?.next_seq??0}async loadTailEntries(e,t){return t<=0?[]:this.db.prepare(`SELECT * FROM (
|
|
82
82
|
SELECT * FROM session_entries WHERE session_id = ? ORDER BY seq DESC LIMIT ?
|
|
83
83
|
) ORDER BY seq ASC`).all(e,t).map($)}async loadEntriesBefore(e,t,n){return t<=0||n<=0?[]:this.db.prepare(`SELECT * FROM (
|
|
84
84
|
SELECT * FROM session_entries
|
|
85
85
|
WHERE session_id = ? AND seq < ?
|
|
86
86
|
ORDER BY seq DESC LIMIT ?
|
|
87
|
-
) ORDER BY seq ASC`).all(e,t,n).map($)}async countEntriesByType(e,t){return this.db.prepare(`SELECT COUNT(*) AS n FROM session_entries WHERE session_id = ? AND type = ?`).get(e,t).n}async putBlobs(e){if(e.length===0)return;let t=this.db.prepare(`INSERT OR IGNORE INTO message_blobs (hash, content, created_at) VALUES (?, ?, ?)`);this.db.transaction(e=>{let n=Date.now();for(let r of e)t.run(r.hash,r.content,n)}).immediate(e)}async getBlobs(e){let t=new Map;for(let n of this.batchInQuery(e,e=>`SELECT hash, content FROM message_blobs WHERE hash IN (${e})`))for(let e of n)t.set(e.hash,e.content);return t}async loadEntriesByIds(e,t){let n=[];for(let r of this.batchInQuery(t,e=>`SELECT * FROM session_entries WHERE session_id = ? AND entry_id IN (${e})`,[e]))n.push(...r);return n.sort((e,t)=>e.seq-t.seq),n.map($)}*batchInQuery(e,t,n=[]){if(e.length!==0)for(let r=0;r<e.length;r+=500){let i=e.slice(r,r+500),a=i.map(()=>`?`).join(`,`);yield this.db.prepare(t(a)).all(...n,...i)}}};function Z(e){return{id:e.id,name:e.name,...e.owner_id==null?{}:{ownerId:e.owner_id},...e.org_id==null?{}:{orgId:e.org_id},createdAt:e.created_at}}function Q(e){return{id:e.id,workspaceKey:e.workspace_key??
|
|
87
|
+
) ORDER BY seq ASC`).all(e,t,n).map($)}async countEntriesByType(e,t){return this.db.prepare(`SELECT COUNT(*) AS n FROM session_entries WHERE session_id = ? AND type = ?`).get(e,t).n}async putBlobs(e){if(e.length===0)return;let t=this.db.prepare(`INSERT OR IGNORE INTO message_blobs (hash, content, created_at) VALUES (?, ?, ?)`);this.db.transaction(e=>{let n=Date.now();for(let r of e)t.run(r.hash,r.content,n)}).immediate(e)}async getBlobs(e){let t=new Map;for(let n of this.batchInQuery(e,e=>`SELECT hash, content FROM message_blobs WHERE hash IN (${e})`))for(let e of n)t.set(e.hash,e.content);return t}async loadEntriesByIds(e,t){let n=[];for(let r of this.batchInQuery(t,e=>`SELECT * FROM session_entries WHERE session_id = ? AND entry_id IN (${e})`,[e]))n.push(...r);return n.sort((e,t)=>e.seq-t.seq),n.map($)}*batchInQuery(e,t,n=[]){if(e.length!==0)for(let r=0;r<e.length;r+=500){let i=e.slice(r,r+500),a=i.map(()=>`?`).join(`,`);yield this.db.prepare(t(a)).all(...n,...i)}}};function Z(e){return{id:e.id,name:e.name,...e.owner_id==null?{}:{ownerId:e.owner_id},...e.org_id==null?{}:{orgId:e.org_id},createdAt:e.created_at}}function Q(e){return{id:e.id,workspaceKey:e.workspace_key??Y,...e.title==null?{}:{title:e.title},...e.title_source==null?{}:{titleSource:e.title_source},...e.parent_session_id==null?{}:{parentSessionId:e.parent_session_id},...e.fork_point==null?{}:{forkPoint:e.fork_point},...e.leaf_id==null?{}:{leafId:e.leaf_id},...e.owner_id==null?{}:{ownerId:e.owner_id},tags:JSON.parse(e.tags),...e.config==null?{}:{config:JSON.parse(e.config)},entryCount:e.next_seq,createdAt:e.created_at,lastActiveAt:e.last_active_at,...e.archived==null?{}:{archived:e.archived===1},...e.pinned==null?{}:{pinned:e.pinned===1},...e.pin_group==null?{}:{pinGroup:e.pin_group}}}function $(e){return{sessionId:e.session_id,seq:e.seq,entryId:e.entry_id,...e.parent_id==null?{}:{parentId:e.parent_id},type:e.type,data:JSON.parse(e.data),createdAt:e.created_at}}var _e=class extends n{turnFlush=`snapshot`;constructor(e){let{userId:t,wsKey:n,...r}=e,i=e.getHeaders;super({...r,wsKey:n,getHeaders:t?async()=>({...await i?.().catch(()=>({}))??{},"X-Otto-User-Id":t}):i,defaultSortBy:`lastActiveAt`,defaultPageSize:I})}get serviceLabel(){return`会话服务`}get endpointFlag(){return`--session-url`}extractId(e){return e.id}async listRecentMeta(e){let t=`/${encodeURIComponent(this.wsKey)}/recent`;return(await(await this.request(`${t}?limit=${encodeURIComponent(String(e))}`,{method:`GET`})).json()).ids}};export{ce as FileSessionPersistence,P as InMemorySession,se as InMemorySessionPersistence,F as InMemorySessionStore,ge as RelationalSessionPersistence,r as RemotePersistenceError,_e as RemoteSessionPersistence,i as RemoteSnapshotConflictError,ie as SESSION_IDLE_TIMEOUT_MS,ae as SESSION_MAX,J as SESSION_MIGRATIONS,I as SESSION_PAGE_SIZE,oe as SESSION_SNAPSHOT_VERSION,q as SessionWriteLeaseDeniedError,X as SqliteSessionRepository,re as createInMemorySessionStore,me as createNoopSessionWriteLeaseManager,pe as createSessionWriteLeaseManager,z as decodeReplacementFromBlobs,R as encodeReplacementToBlobs,V as entryToInput,N as estimateMessageContentBytes,U as explodeSnapshot,fe as hasStrippedReplacements,L as hashMessageContent,K as hydrateStrippedReplacements,W as reassembleSnapshot,B as sessionRowFromSnapshot,de as supportsReplacementHydration};
|
|
88
88
|
//# sourceMappingURL=index.js.map
|