@x-otto/session 0.0.1-alpha.3 → 0.0.1-alpha.5

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/dist/index.d.ts CHANGED
@@ -40,6 +40,22 @@ type SessionEntry<T = unknown> = {
40
40
  id: string;
41
41
  parentId?: string;
42
42
  timestamp: number;
43
+ }
44
+ /**
45
+ * RFC-381 M1:压缩锁 bracket(跨进程 durable 锁)。
46
+ * 压缩开始写 phase:'start'、结束写 phase:'end'(同 token);崩溃后 start 无配对 end
47
+ * 即为孤儿锁(可超时/takeover 接管)。
48
+ * **三类边界**:锁 entry 非消息(buildContext/messages/visibleMessages 均不可见)、
49
+ * 不计 messageCount、不 bump lastActiveAt(派生记账非真实活动)。
50
+ * **additive optional variant——不升 SESSION_SNAPSHOT_VERSION**(旧快照无此条目即无锁)。
51
+ */
52
+ | {
53
+ type: 'compaction-lock';
54
+ id: string;
55
+ parentId?: string; /** 'start' = 持锁;'end' = 释放。 */
56
+ phase: 'start' | 'end'; /** 持锁进程 token(pid + 随机后缀)——end 必须匹配同 token;孤儿判定依据。 */
57
+ token: string;
58
+ timestamp: number;
43
59
  };
44
60
  interface SessionContext<T = unknown> {
45
61
  summary?: string;
@@ -246,6 +262,17 @@ interface Session<T = unknown> {
246
262
  clearContext(options?: {
247
263
  purge?: boolean;
248
264
  }): void;
265
+ /**
266
+ * RFC-381 M1/M2:压缩锁 bracket 写日志(compaction-lock entry,start/end + token)。
267
+ * 可选——旧实现/轻量替身无此能力时 lock 端口应拒绝接线(见 session-compaction-lock)。
268
+ */
269
+ appendCompactionLock?(phase: 'start' | 'end', token: string): void;
270
+ /** RFC-381 M1/M2:当前压缩锁状态(最近一个 compaction-lock entry;无则 undefined)。 */
271
+ compactionLockState?(): {
272
+ phase: 'start' | 'end';
273
+ token: string;
274
+ timestamp: number;
275
+ } | undefined;
249
276
  /**
250
277
  * RFC-194 D3:物理释放最后一个 clear 边界之前的内存驻留(message 条目 splice 移除 +
251
278
  * 非活跃 compaction 的 replacement 剥离;DB append-forever 不动)。幂等;无边界 no-op。
@@ -377,10 +404,21 @@ interface PaginationOptions {
377
404
  }
378
405
  //#endregion
379
406
  //#region src/in-memory-session.d.ts
407
+ /** 注入端口形状(结构类型,与 @x-otto/agent 的 ClockPort/IdPort 兼容)。 */
408
+ interface InMemorySessionPorts {
409
+ clock?: {
410
+ now(): number;
411
+ };
412
+ idGen?: {
413
+ uuid(): string;
414
+ };
415
+ }
380
416
  declare class InMemorySession<T = unknown> implements Session<T> {
381
417
  readonly id: string;
382
418
  private readonly sessionEntries;
383
419
  private readonly entryMap;
420
+ private readonly clock;
421
+ private readonly idGen;
384
422
  /**
385
423
  * RFC-178 D2:会话消息内容字节估算(增量维护,避免每回合 O(n) 重算——lesson_54)。
386
424
  * 覆盖全部变更路径:append 累加 / cap splice 递减 / clearContext purge 递减 /
@@ -419,7 +457,7 @@ declare class InMemorySession<T = unknown> implements Session<T> {
419
457
  * 无需修改。turnSummaries 是后续新增字段(回合完成摘要行持久化,见 TurnSummaryEntry)。
420
458
  */
421
459
  private readonly panelState;
422
- constructor(id: string, parentSessionId?: string, forkPoint?: number);
460
+ constructor(id: string, parentSessionId?: string, forkPoint?: number, ports?: InMemorySessionPorts);
423
461
  private _leafId;
424
462
  get leafId(): string | undefined;
425
463
  /**
@@ -492,6 +530,27 @@ declare class InMemorySession<T = unknown> implements Session<T> {
492
530
  clearContext(options?: {
493
531
  purge?: boolean;
494
532
  }): void;
533
+ /**
534
+ * RFC-381 M1:压缩锁 bracket 写日志(append-only,历史不可变)。
535
+ * 写入 `compaction-lock` 结构 entry(phase start/end + token)。
536
+ * **三类边界**:不 bump messageCount、不 markActivity(派生记账非真实活动)、
537
+ * buildContext/messages/visibleMessages 均不可见(非 message 类型天然被过滤)。
538
+ * 落库由持久化层照常走(type+data 通用行,零序列化改动)。
539
+ */
540
+ appendCompactionLock(phase: 'start' | 'end', token: string): void;
541
+ /**
542
+ * RFC-381 M1:当前压缩锁状态(最近一个 compaction-lock entry)。
543
+ * - undefined:无锁(从未加锁或已 end);
544
+ * - phase 'end':已释放;
545
+ * - phase 'start':持锁中(token 是持有者;跨进程据此判定孤儿——start 长时间无
546
+ * 配对 end 即崩溃残留,可超时/takeover)。
547
+ * 只读当前 leaf 分支(walkBranch),不触碰完整转录。
548
+ */
549
+ compactionLockState(): {
550
+ phase: 'start' | 'end';
551
+ token: string;
552
+ timestamp: number;
553
+ } | undefined;
495
554
  /**
496
555
  * RFC-194 D3:物理释放最后一个 clear 边界之前的内存驻留(DB append-forever 不动)。
497
556
  * 供持久化层在「clear 边界确认落盘成功后」调用(顺序保证见 RFC-194 D2——先 save
@@ -736,6 +795,8 @@ declare function estimateMessageContentBytes(message: unknown): number;
736
795
  //#region src/store.d.ts
737
796
  declare class InMemorySessionStore<T = unknown> implements SessionStore<T> {
738
797
  private readonly sessions;
798
+ private readonly ports?;
799
+ constructor(ports?: InMemorySessionPorts);
739
800
  createSession(id?: string): Promise<Session<T>>;
740
801
  getSession(id: string): Session<T> | undefined;
741
802
  listSessions(): ReadonlyArray<Session<T>>;
@@ -743,7 +804,7 @@ declare class InMemorySessionStore<T = unknown> implements SessionStore<T> {
743
804
  deleteSession(id: string): Promise<boolean>;
744
805
  forkSession(sourceId: string, newId?: string): Promise<Session<T> | undefined>;
745
806
  }
746
- declare function createInMemorySessionStore<T = unknown>(): SessionStore<T>;
807
+ declare function createInMemorySessionStore<T = unknown>(ports?: InMemorySessionPorts): SessionStore<T>;
747
808
  //#endregion
748
809
  //#region src/memory-persistence.d.ts
749
810
  /**
@@ -797,13 +858,6 @@ declare class FileSessionPersistence<T = unknown> extends DiskPersistence<Sessio
797
858
  * 本层仍只认结构化行(workspaces / sessions / session_entries),**不依赖 SessionSnapshot 领域形状**
798
859
  * (snapshot↔rows 桥在 relational-bridge)。change_log(entry 级)属后续阶段C(gated),本层不建。
799
860
  */
800
- interface WorkspaceRow {
801
- readonly id: string;
802
- readonly name: string;
803
- readonly ownerId?: string;
804
- readonly orgId?: string;
805
- readonly createdAt: number;
806
- }
807
861
  interface SessionRow {
808
862
  readonly id: string;
809
863
  /** 分区第一维(= ws_<id>);默认 'default'。 */
@@ -837,7 +891,7 @@ interface SessionRow {
837
891
  /** 置顶分组名(RFC-158)。仅 pinned=true 时生效;缺省落入默认组。 */
838
892
  readonly pinGroup?: string;
839
893
  }
840
- type SessionEntryType = 'message' | 'compaction' | 'clear';
894
+ type SessionEntryType = 'message' | 'compaction' | 'clear' | 'compaction-lock';
841
895
  /** 追加输入:seq 由仓储发号,调用方只给 entryId(幂等键)+ 内容。 */
842
896
  interface EntryInput {
843
897
  /** 客户端生成(规则0/1 幂等键);(sessionId, entryId) 唯一。 */
@@ -854,20 +908,6 @@ interface EntryRow extends EntryInput {
854
908
  readonly seq: number;
855
909
  }
856
910
  interface SessionRepository {
857
- /**
858
- * ⚠️ **DORMANT(resume/workspace 关联审计,2026-07-11 核实)**:`workspaces` 表 + 本三方法
859
- * 当前**零生产调用方**(仅 `sqlite-session-repository.test.ts` 覆盖)——对应 RFC-034 M57
860
- * 里程碑设计的"web-ui workspaces CRUD"(`POST/GET/DELETE /workspaces`),但该 HTTP 路由
861
- * 从未实现,只落地了本层 SQLite 原语。当前 local workspace 身份完全靠 `.otto/workspace.json`
862
- * marker(`@x-otto/workspace` 包)+ `sessions.workspace_key` 列分区,不依赖本表。
863
- * 参考 RFC-067 M115-04(workspace 相关代码"现实修正:不强删活包"的既有判定)与
864
- * M115-02(remote-persistence-server 删除前需产品确认)先例——**接它前先把 web-ui
865
- * workspaces CRUD 路由一并接上**,删它前先问是否已确认 web-ui 落地路线放弃该设计。
866
- * 勿孤立增删本三方法。
867
- */
868
- upsertWorkspace(ws: WorkspaceRow): Promise<void>;
869
- getWorkspace(id: string): Promise<WorkspaceRow | null>;
870
- listWorkspaces(): Promise<WorkspaceRow[]>;
871
911
  createSession(row: SessionRow): Promise<void>;
872
912
  /**
873
913
  * 轻量排序 id 列表(RFC-154 D1)——只读 sessions 表的 `id`/`last_active_at`/`archived` 列,
@@ -1042,6 +1082,13 @@ interface SessionWriteLeaseOptions {
1042
1082
  renewEveryMs?: number;
1043
1083
  /** 是否注册 process exit 钩子同步释放(默认 true;测试注入 false 避免跨用例泄漏)。 */
1044
1084
  installExitHook?: boolean;
1085
+ /**
1086
+ * 确定性 token 生成端口(M-2)。**token 随机性是安全特性(防伪造)**,生产缺省仍走
1087
+ * `crypto.randomUUID()`;此注入仅在测试 / 确定性重放场景使用,不得在生产路径关闭随机性。
1088
+ */
1089
+ idGen?: {
1090
+ uuid(): string;
1091
+ };
1045
1092
  }
1046
1093
  declare function createSessionWriteLeaseManager(options: SessionWriteLeaseOptions): SessionWriteLeaseManager;
1047
1094
  /**
@@ -1172,6 +1219,8 @@ declare class RelationalSessionPersistence<T = unknown> implements SessionPersis
1172
1219
  declare function sessionRowFromSnapshot<T>(snapshot: SessionSnapshot<T>, workspaceKey: string): SessionRow;
1173
1220
  /** 一条 SessionEntry → 仓储输入(id/parentId/type/timestamp 进列,其余进 data)。 */
1174
1221
  declare function entryToInput<T>(e: SessionEntry<T>): EntryInput;
1222
+ /** 一行 → SessionEntry(列还原 + data 展开)。 */
1223
+ declare function rowToEntry<T>(r: EntryRow): SessionEntry<T>;
1175
1224
  /** 炸开 snapshot 到仓储行(createSession + 逐条 appendEntry,保序 + parentId/leaf/config)。 */
1176
1225
  declare function explodeSnapshot<T>(snapshot: SessionSnapshot<T>, workspaceKey: string, repo: SessionRepository): Promise<void>;
1177
1226
  /** RFC-159 D4:尾窗口加载选项。 */
@@ -1284,9 +1333,6 @@ declare class SqliteSessionRepository implements SessionRepository {
1284
1333
  * 已有的 entries 不删(幂等 append 可能产生重复,appendEntry 幂等去重可容忍),
1285
1334
  * 仅当 DB 中的条目数 < 归档条目数时追加缺失部分。 */
1286
1335
  restoreArchivedSession(sessionId: string): Promise<number>;
1287
- upsertWorkspace(ws: WorkspaceRow): Promise<void>;
1288
- getWorkspace(id: string): Promise<WorkspaceRow | null>;
1289
- listWorkspaces(): Promise<WorkspaceRow[]>;
1290
1336
  createSession(row: SessionRow): Promise<void>;
1291
1337
  touchSession(id: string, leafId: string | undefined, lastActiveAt: number, title?: string, titleSource?: 'custom' | 'ai' | 'derived', config?: unknown, archived?: boolean, pinned?: boolean, pinGroup?: string): Promise<{
1292
1338
  leafPersisted: boolean;
@@ -1375,5 +1421,5 @@ declare class RemoteSessionPersistence<T = unknown> extends RemotePersistence<Se
1375
1421
  listRecentMeta(limit: number): Promise<string[]>;
1376
1422
  }
1377
1423
  //#endregion
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 };
1424
+ 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, createInMemorySessionStore, createNoopSessionWriteLeaseManager, createSessionWriteLeaseManager, decodeReplacementFromBlobs, encodeReplacementToBlobs, entryToInput, estimateMessageContentBytes, explodeSnapshot, hasStrippedReplacements, hashMessageContent, hydrateStrippedReplacements, reassembleSnapshot, rowToEntry, sessionRowFromSnapshot, supportsReplacementHydration };
1379
1425
  //# sourceMappingURL=index.d.ts.map
@@ -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;AAA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AAgB,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;;;;;;AA4BN;;EApBM,IAAA;EAAe,EAAA;EAAY,QAAA;EAAmB,SAAA;AAAA;;;;AA8BpD;;;;;;EApBM,IAAA;EACA,EAAA;EACA,QAAA,WAoCJ;EAlCI,KAAA,mBAqCJ;EAnCI,KAAA;EACA,SAAA;AAAA;AAAA,UAGW,cAAA;EACf,OAAA;EACA,QAAA,EAAU,CAAA;AAAA;;;AA0EZ;;;UAlEiB,sBAAA;EACf,WAAA;EAmEA;;;;;AASF;;;;;;;EA/DE,QAAA;EACA,KAAA;EACA,SAAA;EACA,aAAA;EACA,qBAAA;EACA,SAAA;EAqEyB;EAnEzB,OAAA;EAqEA;;;;EAhEA,YAAA;EAqEA;EAnEA,YAAA;EAmEU;AAOZ;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AAU,eAAA,CAAgB,CAAA;EdT1B;;;;;;EcmBvB,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,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(`
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 x,createWriteStream as S,existsSync as C,mkdirSync as w,openSync as T,readFileSync as ee,renameSync as te,rmSync as ne,statSync as E,unlinkSync as D,utimesSync as O,writeSync as k}from"node:fs";import{createGzip as re,gunzipSync as ie}from"node:zlib";const A={derived:0,ai:1,custom:2};function j(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}const M={now:()=>Date.now()},N={uuid:()=>crypto.randomUUID()};var P=class{sessionEntries=[];entryMap=new Map;clock;idGen;_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+=j(t.message);else if(t.type===`compaction`&&t.replacement)for(let n of t.replacement)e+=j(n);return{counter:this._estimatedContentBytes,recomputed:e,drift:e-this._estimatedContentBytes}}meta;panelState={};constructor(e,t,n,r){this.id=e,this.clock=r?.clock??M,this.idGen=r?.idGen??N;let i=this.clock.now();this.meta={createdAt:i,lastActiveAt:i,messageCount:0,compactionCount:0,parentSessionId:t,forkPoint:n,tags:[]}}_leafId=void 0;get leafId(){return this._leafId}markActivity(){this.meta.lastActiveAt=this.clock.now()}append(e){let t={type:`message`,id:this.idGen.uuid(),parentId:this._leafId,message:e,timestamp:this.clock.now()};this._leafId=t.id,this.sessionEntries.push(t),this.entryMap.set(t.id,t),this.meta.messageCount++,this.markActivity(),this._estimatedContentBytes+=j(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-=j(e.message))}compact(e,t){let n=this.getBranchMessageEntries();if(t<=0||t>n.length)return;let r={type:`compaction`,id:this.idGen.uuid(),parentId:this._leafId,summary:e,compactedCount:t,timestamp:this.clock.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:this.idGen.uuid(),parentId:this._leafId,summary:e,compactedCount:t.length,replacement:[...t],timestamp:this.clock.now()};for(let e of t)this._estimatedContentBytes+=j(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-=j(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:this.idGen.uuid(),parentId:this._leafId,timestamp:this.clock.now()};this.sessionEntries.push(t),this.entryMap.set(t.id,t),this.markActivity(),this._leafId=t.id,e?.purge===!0&&this.purgeBeforeBoundary(t.id)}appendCompactionLock(e,t){let n={type:`compaction-lock`,id:this.idGen.uuid(),parentId:this._leafId,phase:e,token:t,timestamp:this.clock.now()};this.sessionEntries.push(n),this.entryMap.set(n.id,n),this._leafId=n.id}compactionLockState(){let e=this.walkBranch();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.type===`compaction-lock`)return{phase:n.phase,token:n.token,timestamp:n.timestamp}}}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-=j(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:A[this.meta.titleSource];return A[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+=j(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-=j(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-=j(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-=j(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+=j(t.message);else if(t.type===`compaction`&&t.replacement)for(let e of t.replacement)r+=j(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;ports;constructor(e){this.ports=e}async createSession(e=crypto.randomUUID()){let t=new P(e,void 0,void 0,this.ports);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,this.ports);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 ae(e){return new F(e)}const oe=f(process.env.OTTO_SESSION_IDLE_TIMEOUT_MS,1800*1e3),se=f(process.env.OTTO_SESSION_MAX,50),I=f(process.env.OTTO_SESSION_PAGE_SIZE,20),L=f(process.env.OTTO_SESSION_SNAPSHOT_VERSION,1);var R=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)}},z=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 B(e){return`sha256:${y(`sha256`).update(e,`utf-8`).digest(`hex`)}`}async function V(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(B);await n.putBlobs(i.map((e,t)=>({hash:a[t],content:e})));let{replacement:o,...s}=t;return{...s,replacementHashes:a}}async function H(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 U(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 W(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 G(e){return{type:e.type,id:e.entryId,...e.parentId==null?{}:{parentId:e.parentId},timestamp:e.createdAt,...e.data}}async function ce(e,t,n){await n.createSession(U(e,t));for(let t of e.entries)await n.appendEntry(e.id,W(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 K(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=>G(e)):await t.getEntryCount(e)>n.maxEntries?(i=(await t.loadTailEntries(e,n.maxEntries)).map(e=>G(e)),a=!0,n.canStartHistory&&(i=ue(i,n.canStartHistory))):i=(await t.loadEntries(e)).map(e=>G(e)),n?.stripInactiveReplacements?(i=le(i,r.leafId??void 0),i=await q(i,t,{onlyUnstripped:!0})):i=await q(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 q(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 H(`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 J(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 H(`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 Y=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`}};const pe={uuid:()=>b()};function me(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(ee(o(e),`utf-8`).trim())}catch{return null}},f=e=>s(e)?.token??null,p=(t,n)=>{try{w(e.lockDir,{recursive:!0});let r=T(o(t),`wx`);try{k(r,u(n,process.pid,a))}finally{x(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(n){if(i)return!1;let a=r.get(n);if(a){if(f(n)===a.token)return!0;v(n)}let c=(e.idGen??pe).uuid();if(p(n,c))return g(n,c),!0;let l=s(n),u;try{u=E(o(n)).mtimeMs}catch{return p(n,c)?(g(n,c),!0):!1}if(l!==null&&h(l)||!(l!==null&&m(l))&&Date.now()-u<=t)return!1;let d=`${o(n)}.stale-${b()}`;try{te(o(n),d),ne(d,{force:!0})}catch{return!1}return p(n,c)?(g(n,c),!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 he(){return{acquire:()=>!0,release:()=>{},releaseAll:()=>{},isOwner:()=>!0,peekLockedByOther:()=>!1,inspect:()=>({locked:!1}),forceRelease:()=>{},close:()=>{}}}const ge={warn:()=>{}};var _e=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??ge,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 Y(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 Y(e.id);await this.repo.createSession(U(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=W(e.entries[t]),r=await V(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 K(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 J(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 X=[{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,12 @@ 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
- `)}}],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
- `).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
- VALUES (?, ?, ?, ?, ?)
52
- ON CONFLICT (id) DO UPDATE SET
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
48
+ `)}}],Z=`default`;var ve=class{db;archiveDir;ephemeral;constructor(e){this.db=a(e.dbPath,e.wal!==!1,X),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`);C(this.archiveDir)||w(this.archiveDir,{recursive:!0});let n=await this.loadEntries(e),r=re(),i=S(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(!C(t))return 0;let n=ie(await p(t)).toString(`utf-8`).trim().split(`
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 createSession(e){this.db.prepare(`INSERT INTO sessions
54
51
  (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
52
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)
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
53
+ ON CONFLICT (id) DO NOTHING`).run(e.id,e.workspaceKey||Z,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
54
  leaf_id = ?,
58
55
  last_active_at = ?,
59
56
  title = COALESCE(?, title),
@@ -71,18 +68,18 @@ import{DiskPersistence as e,MemoryPersistenceBase as t,RemotePersistence as n,Re
71
68
  pinned = COALESCE(?, pinned),
72
69
  pin_group = COALESCE(?, pin_group)
73
70
  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, '${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}') = ?
71
+ WHERE COALESCE(workspace_key, '${Z}') = ?
72
+ ORDER BY last_active_at DESC`).all(e||Z).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
73
+ WHERE COALESCE(workspace_key, '${Z}') = ?
77
74
  AND COALESCE(archived, 0) = 0
78
75
  AND next_seq > 0
79
76
  ORDER BY last_active_at DESC
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)
77
+ LIMIT ?`).all(e||Z,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
78
  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
79
  SELECT * FROM session_entries WHERE session_id = ? ORDER BY seq DESC LIMIT ?
83
80
  ) ORDER BY seq ASC`).all(e,t).map($)}async loadEntriesBefore(e,t,n){return t<=0||n<=0?[]:this.db.prepare(`SELECT * FROM (
84
81
  SELECT * FROM session_entries
85
82
  WHERE session_id = ? AND seq < ?
86
83
  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??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};
84
+ ) 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 Q(e){return{id:e.id,workspaceKey:e.workspace_key??Z,...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 ye=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{z as FileSessionPersistence,P as InMemorySession,R as InMemorySessionPersistence,F as InMemorySessionStore,_e as RelationalSessionPersistence,r as RemotePersistenceError,ye as RemoteSessionPersistence,i as RemoteSnapshotConflictError,oe as SESSION_IDLE_TIMEOUT_MS,se as SESSION_MAX,X as SESSION_MIGRATIONS,I as SESSION_PAGE_SIZE,L as SESSION_SNAPSHOT_VERSION,Y as SessionWriteLeaseDeniedError,ve as SqliteSessionRepository,ae as createInMemorySessionStore,he as createNoopSessionWriteLeaseManager,me as createSessionWriteLeaseManager,H as decodeReplacementFromBlobs,V as encodeReplacementToBlobs,W as entryToInput,j as estimateMessageContentBytes,ce as explodeSnapshot,fe as hasStrippedReplacements,B as hashMessageContent,J as hydrateStrippedReplacements,K as reassembleSnapshot,G as rowToEntry,U as sessionRowFromSnapshot,de as supportsReplacementHydration};
88
85
  //# sourceMappingURL=index.js.map