@tangle-network/sdk-session-persistence 0.0.0-stage → 0.7.1

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/LICENSE ADDED
@@ -0,0 +1,11 @@
1
+ Copyright (c) 2025 Tangle Network
2
+
3
+ All rights reserved.
4
+
5
+ This software and associated documentation files (the "Software") are proprietary
6
+ and confidential. No part of this Software may be reproduced, distributed, or
7
+ transmitted in any form or by any means, including photocopying, recording, or
8
+ other electronic or mechanical methods, without the prior written permission of
9
+ Tangle Network.
10
+
11
+ For licensing inquiries, contact: hello@tangle.tools
@@ -0,0 +1,307 @@
1
+ import { FileHandle } from "node:fs/promises";
2
+ import { AgentExecutionInput, ToolState } from "@tangle-network/agent-interface";
3
+
4
+ //#region src/durable-write.d.ts
5
+ /** A durable record is owner-only unless the caller shares it with another uid. */
6
+ declare const DURABLE_FILE_MODE = 384;
7
+ /** The `<file>.tmp-<hex>` sibling a durable write fills before its rename. */
8
+ declare const temporarySibling: (target: string) => string;
9
+ declare function syncDirectory(directory: string): Promise<void>;
10
+ interface DurableWriteOptions {
11
+ /** The file's exact mode; owner-only unless the caller shares it. */
12
+ mode?: number;
13
+ /** The uid and gid the file carries before it becomes visible. */
14
+ owner?: {
15
+ uid: number;
16
+ gid: number;
17
+ };
18
+ /**
19
+ * The target's directory, held open. `target` is then a name in it, and the
20
+ * write, rename and sync go through the handle, so an ancestor swapped under
21
+ * the caller cannot redirect them.
22
+ */
23
+ directory?: FileHandle;
24
+ }
25
+ /**
26
+ * Durably replaces `target` with `contents`; its directory must exist. A crash
27
+ * can leave a `.tmp-` sibling that readers skip.
28
+ */
29
+ declare function writeFileDurably(target: string, contents: string, {
30
+ mode,
31
+ owner,
32
+ directory
33
+ }?: DurableWriteOptions): Promise<void>;
34
+ //#endregion
35
+ //#region src/types.d.ts
36
+ /**
37
+ * A persisted session record.
38
+ */
39
+ interface PersistedSession {
40
+ /** Unique session identifier */
41
+ id: string;
42
+ /** Parent session ID (for forked sessions) */
43
+ parentId?: string;
44
+ /** Message ID where fork occurred */
45
+ forkMessageId?: string;
46
+ /** Workspace root path */
47
+ workspaceRoot: string;
48
+ /** Provider-specific session ID */
49
+ providerSessionId?: string;
50
+ /**
51
+ * Runtime home that minted `providerSessionId`. Provider session data
52
+ * lives under that home's data dirs, so a reader running with a DIFFERENT
53
+ * runtime home cannot resume the session and must start fresh. Absent
54
+ * means "not recorded" (pre-field records or adapters without a private
55
+ * home) — readers then assume same-home.
56
+ */
57
+ providerSessionHome?: string;
58
+ /** When the session was created */
59
+ createdAt: Date;
60
+ /** When the session was last accessed */
61
+ lastAccessedAt: Date;
62
+ }
63
+ /**
64
+ * Text content part (simplified for persistence).
65
+ */
66
+ interface PersistedTextPart {
67
+ type: "text";
68
+ text: string;
69
+ }
70
+ /**
71
+ * Tool invocation content part (simplified for persistence).
72
+ * Uses consistent field names with agent-interface.
73
+ */
74
+ interface PersistedToolPart {
75
+ type: "tool";
76
+ /** Tool name - consistent with agent-interface */
77
+ tool: string;
78
+ /** Tool call ID - consistent with agent-interface */
79
+ callID: string;
80
+ /** Tool execution state */
81
+ state: ToolState;
82
+ }
83
+ /**
84
+ * Reasoning/thinking content part (simplified for persistence).
85
+ */
86
+ interface PersistedReasoningPart {
87
+ type: "reasoning";
88
+ text: string;
89
+ }
90
+ /**
91
+ * File reference content part (simplified for persistence).
92
+ */
93
+ interface PersistedFilePart {
94
+ type: "file";
95
+ /**
96
+ * Deterministic id from the stream layer (see `deterministicFilePartId` in
97
+ * sdk-provider-cli-base). Consumed by downstream persistence (the sidecar's
98
+ * message rollup) to upsert the live-streamed copy of this part instead of
99
+ * appending a duplicate when the same file is announced again later in the
100
+ * same message.
101
+ */
102
+ id?: string;
103
+ filename?: string;
104
+ mediaType?: string;
105
+ url?: string;
106
+ }
107
+ /**
108
+ * Union of all message part types for persistence.
109
+ */
110
+ type MessagePart = PersistedTextPart | PersistedToolPart | PersistedReasoningPart | PersistedFilePart;
111
+ /**
112
+ * A persisted message record.
113
+ */
114
+ interface PersistedMessage {
115
+ /** Unique message identifier */
116
+ id: string;
117
+ /** Session this message belongs to */
118
+ sessionId: string;
119
+ /** Message role */
120
+ role: "user" | "assistant" | "system";
121
+ /** Message content parts */
122
+ parts: MessagePart[];
123
+ /** When the message was created */
124
+ timestamp: Date;
125
+ /** Token usage statistics */
126
+ tokenUsage?: {
127
+ inputTokens?: number;
128
+ outputTokens?: number;
129
+ };
130
+ /** Additional metadata */
131
+ metadata?: Record<string, unknown>;
132
+ }
133
+ /** Fields a session may be created with. */
134
+ type CreatePersistedSessionOptions = Pick<PersistedSession, "workspaceRoot" | "providerSessionId" | "providerSessionHome"> & {
135
+ /** Optional explicit session ID (random UUID if omitted) */id?: string;
136
+ };
137
+ /** Options for listing sessions. */
138
+ interface ListSessionsOptions {
139
+ /** Filter by workspace root */
140
+ workspaceRoot?: string;
141
+ }
142
+ /**
143
+ * Options for forking a session.
144
+ */
145
+ interface ForkSessionOptions {
146
+ /**
147
+ * Identifier for the forked session. Callers that address sessions by an
148
+ * external id (the sidecar addresses CLI-backend turns by its own session
149
+ * id) pass that id here so later turns find the forked record. The store
150
+ * rejects an id that already names a session. Absent means a random UUID.
151
+ */
152
+ id?: string;
153
+ /** Message ID to fork at (if not provided, forks at latest message) */
154
+ messageId?: string;
155
+ /** New workspace root (if different from parent) */
156
+ workspaceRoot?: string;
157
+ }
158
+ /**
159
+ * Options for listing messages.
160
+ */
161
+ interface ListPersistedMessagesOptions {
162
+ /** Refuse a missing index or indexed message during exact transcript replay. */
163
+ requireComplete?: boolean;
164
+ /** Only for a new external ID: a wholly absent directory means no prior transcript. */
165
+ allowAbsent?: boolean;
166
+ /** Maximum number of messages to return */
167
+ limit?: number;
168
+ /** Offset for pagination */
169
+ offset?: number;
170
+ /** Stop after this message; unknown ids throw. Later messages are never read. */
171
+ through?: string;
172
+ }
173
+ /**
174
+ * Session store interface.
175
+ */
176
+ interface SessionStore {
177
+ /** Create a new session */
178
+ create(options: CreatePersistedSessionOptions): Promise<PersistedSession>;
179
+ /** Get a session by ID */
180
+ get(sessionId: string): Promise<PersistedSession | null>;
181
+ /** Update a session; an empty update only refreshes lastAccessedAt. */
182
+ update(sessionId: string, updates: Partial<Omit<CreatePersistedSessionOptions, "id" | "workspaceRoot">>): Promise<PersistedSession | null>;
183
+ /** Delete a session record; its messages belong to the message store. */
184
+ delete(sessionId: string): Promise<boolean>;
185
+ /** List sessions */
186
+ list(options?: ListSessionsOptions): Promise<PersistedSession[]>;
187
+ /** Fork a session */
188
+ fork(sessionId: string, options?: ForkSessionOptions): Promise<PersistedSession>;
189
+ }
190
+ /** Fields a message is appended with. */
191
+ type CreateMessageOptions = Pick<PersistedMessage, "sessionId" | "role" | "parts" | "tokenUsage" | "metadata"> & {
192
+ /** Stable provider message ID when the caller owns one. */id?: string; /** Original event time when importing a completed transcript. */
193
+ timestamp?: Date;
194
+ };
195
+ /**
196
+ * Message store interface.
197
+ */
198
+ interface MessageStore {
199
+ /** Append a new message */
200
+ append(options: CreateMessageOptions): Promise<PersistedMessage>;
201
+ /** List messages for a session */
202
+ list(sessionId: string, options?: ListPersistedMessagesOptions): Promise<PersistedMessage[]>;
203
+ /** Clear all messages for a session */
204
+ clear(sessionId: string): Promise<void>;
205
+ /**
206
+ * Record a complete, empty history for a session that has no message
207
+ * directory. An existing complete history is unchanged; a directory without
208
+ * an index is refused rather than declared complete.
209
+ */
210
+ initialize(sessionId: string): Promise<void>;
211
+ }
212
+ /**
213
+ * Configuration for persistence storage.
214
+ */
215
+ interface PersistenceConfig {
216
+ /** Base storage path */
217
+ storagePath: string;
218
+ /** Storage subdirectory name under `storagePath`, owned by the provider */
219
+ storageDir: string;
220
+ }
221
+ //#endregion
222
+ //#region src/fork.d.ts
223
+ /** Higher bounded budget for explicit secret-profile history migration. */
224
+ declare const MAX_SECRET_PROFILE_REPLAY_CHARS: number;
225
+ /**
226
+ * Wrapper tag and preamble for a restored session's transcript block. Used
227
+ * when a session's durable history exists but its provider-native session
228
+ * cannot be resumed (a workspace restored from a snapshot), so the next turn
229
+ * replays the history into the fresh provider session it starts.
230
+ */
231
+ declare const RESTORED_SESSION_CONTEXT_TAG = "restored-session-context";
232
+ declare const RESTORED_SESSION_CONTEXT_PREAMBLE = "You are continuing a restored session. The transcript below is this session's durable history; the provider session that produced it is gone. Treat it as prior conversation context, then answer the new request.";
233
+ /** Presentation controls for a transcript context block. */
234
+ type TranscriptContextOptions = {
235
+ /** Character budget for the block. Default: MAX_FORK_CONTEXT_CHARS. */maxChars?: number; /** Sentence that tells the model where the transcript came from. */
236
+ preamble?: string; /** Tag that wraps the transcript entries. */
237
+ tag?: string;
238
+ };
239
+ /**
240
+ * Builds the execution-only context block a fresh provider session receives
241
+ * on its first turn, from the session's persisted transcript. Selection
242
+ * walks from the newest message backwards under `maxChars`; the oldest kept
243
+ * entry may be truncated from its front. Returns undefined when no message
244
+ * renders any content. Defaults present the block as a fork; a restored
245
+ * session passes the RESTORED_SESSION_CONTEXT_* values.
246
+ */
247
+ declare function buildForkContextBlock(messages: Array<Pick<PersistedMessage, "role" | "parts">>, options?: TranscriptContextOptions): string | undefined;
248
+ /** Refuse an incomplete replay when a native session must carry exact history. */
249
+ declare function buildCompleteForkContextBlock(messages: Array<Pick<PersistedMessage, "role" | "parts">>, options?: TranscriptContextOptions): string | undefined;
250
+ /** Result of a session fork operation. */
251
+ interface SessionForkResult {
252
+ /** The newly forked session */
253
+ session: PersistedSession;
254
+ /** Number of messages copied */
255
+ messagesCopied: number;
256
+ }
257
+ /**
258
+ * Forks a session along with its messages up to and including
259
+ * `options.messageId` (all messages when absent). A failed copy deletes the
260
+ * forked session and its partial messages before rethrowing.
261
+ */
262
+ declare function forkSessionWithMessages(sessionStore: SessionStore, messageStore: MessageStore, sessionId: string, options?: ForkSessionOptions): Promise<SessionForkResult>;
263
+ //#endregion
264
+ //#region src/message-ids.d.ts
265
+ /**
266
+ * Stable provider-store identifiers for one sidecar execution.
267
+ *
268
+ * The sidecar durable recorder and provider-owned message store must use the
269
+ * same identifiers. Otherwise the message route cannot join their records.
270
+ */
271
+ interface ProviderMessageIds {
272
+ userMessageId: string;
273
+ assistantMessageId: string;
274
+ }
275
+ type ProviderMessageInput = Pick<AgentExecutionInput, "systemPrompt"> & {
276
+ providerMessageIds?: ProviderMessageIds;
277
+ };
278
+ /**
279
+ * Derive the two message identifiers owned by one execution.
280
+ *
281
+ * Sidecar executions use their execution id as the assistant message id.
282
+ * The user message uses the same id with a role suffix, so retries overwrite
283
+ * one record instead of adding a second index entry.
284
+ */
285
+ declare function providerMessageIdsForExecution(executionId: string | undefined): ProviderMessageIds | undefined;
286
+ /**
287
+ * Read the internal provider-message identity carried through the adapter
288
+ * input by the sidecar. Public AgentExecutionInput intentionally stays
289
+ * unchanged; this is a private cross-package transport field.
290
+ */
291
+ declare function readProviderMessageIds(input: ProviderMessageInput): ProviderMessageIds | undefined;
292
+ //#endregion
293
+ //#region src/message-store.d.ts
294
+ /**
295
+ * Creates a file-based message store. Each session keeps one JSON file per
296
+ * message plus `_index.json`, which owns message order.
297
+ */
298
+ declare function createMessageStore(config: PersistenceConfig): MessageStore;
299
+ //#endregion
300
+ //#region src/session-store.d.ts
301
+ /**
302
+ * Creates a file-based session store.
303
+ */
304
+ declare function createSessionStore(config: PersistenceConfig): SessionStore;
305
+ //#endregion
306
+ export { DURABLE_FILE_MODE, type DurableWriteOptions, MAX_SECRET_PROFILE_REPLAY_CHARS, type MessagePart, type MessageStore, type PersistedFilePart, type PersistedMessage, type PersistedReasoningPart, type PersistedSession, type PersistedTextPart, type ProviderMessageIds, RESTORED_SESSION_CONTEXT_PREAMBLE, RESTORED_SESSION_CONTEXT_TAG, type SessionStore, buildCompleteForkContextBlock, buildForkContextBlock, createMessageStore, createSessionStore, forkSessionWithMessages, providerMessageIdsForExecution, readProviderMessageIds, syncDirectory, temporarySibling, writeFileDurably };
307
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,413 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import * as fs$1 from "node:fs/promises";
3
+ import fs from "node:fs/promises";
4
+ import * as path from "node:path";
5
+ import { dirname } from "node:path";
6
+ //#region src/durable-write.ts
7
+ /** A durable record is owner-only unless the caller shares it with another uid. */
8
+ const DURABLE_FILE_MODE = 384;
9
+ /** The `<file>.tmp-<hex>` sibling a durable write fills before its rename. */
10
+ const temporarySibling = (target) => `${target}.tmp-${randomBytes(6).toString("hex")}`;
11
+ async function syncDirectory(directory) {
12
+ const handle = await fs.open(directory, "r");
13
+ try {
14
+ await handle.sync();
15
+ } finally {
16
+ await handle.close();
17
+ }
18
+ }
19
+ /**
20
+ * Durably replaces `target` with `contents`; its directory must exist. A crash
21
+ * can leave a `.tmp-` sibling that readers skip.
22
+ */
23
+ async function writeFileDurably(target, contents, { mode = 384, owner, directory } = {}) {
24
+ if (directory && !/^(?!\.\.?$)[^/]+$/.test(target)) throw new Error(`Not an entry name in the open directory: ${target}`);
25
+ const path = directory ? `/proc/self/fd/${directory.fd}/${target}` : target;
26
+ const temporary = temporarySibling(path);
27
+ try {
28
+ const handle = await fs.open(temporary, "wx", mode);
29
+ try {
30
+ if (owner) await handle.chown(owner.uid, owner.gid);
31
+ await handle.chmod(mode);
32
+ await handle.writeFile(contents, "utf-8");
33
+ await handle.sync();
34
+ } finally {
35
+ await handle.close();
36
+ }
37
+ await fs.rename(temporary, path);
38
+ } catch (error) {
39
+ await fs.rm(temporary, { force: true }).catch(() => void 0);
40
+ throw error;
41
+ }
42
+ await (directory ? directory.sync() : syncDirectory(dirname(path)));
43
+ }
44
+ //#endregion
45
+ //#region src/fork.ts
46
+ /**
47
+ * Character budget for a fork-context block. Keeps the replayed transcript
48
+ * inside a safe share of the model prompt.
49
+ */
50
+ const MAX_FORK_CONTEXT_CHARS = 24e3;
51
+ /** Higher bounded budget for explicit secret-profile history migration. */
52
+ const MAX_SECRET_PROFILE_REPLAY_CHARS = 64 * 1024;
53
+ /**
54
+ * Wrapper tag and preamble for a restored session's transcript block. Used
55
+ * when a session's durable history exists but its provider-native session
56
+ * cannot be resumed (a workspace restored from a snapshot), so the next turn
57
+ * replays the history into the fresh provider session it starts.
58
+ */
59
+ const RESTORED_SESSION_CONTEXT_TAG = "restored-session-context";
60
+ const RESTORED_SESSION_CONTEXT_PREAMBLE = "You are continuing a restored session. The transcript below is this session's durable history; the provider session that produced it is gone. Treat it as prior conversation context, then answer the new request.";
61
+ const FORK_CONTEXT_TAG = "forked-session-context";
62
+ const FORK_CONTEXT_PREAMBLE = "You are continuing from a forked session. The transcript below was copied from the parent session up to the fork point. Treat it as prior conversation context, then answer the new request.";
63
+ /**
64
+ * Renders one persisted message as a `role:\ncontent` transcript entry.
65
+ * Non-text parts collapse to short markers. Returns "" for an empty message.
66
+ */
67
+ function formatForkContextMessage(message) {
68
+ const content = message.parts.map((part) => {
69
+ if (part.type === "text" || part.type === "reasoning") return part.text;
70
+ if (part.type === "file") return `[file: ${part.filename ?? part.url ?? "attached"}]`;
71
+ return `[tool: ${part.tool} ${part.state.status}]`;
72
+ }).filter(Boolean).join("\n");
73
+ return content.trim() ? `${message.role}:\n${content.trim()}` : "";
74
+ }
75
+ /**
76
+ * Builds the execution-only context block a fresh provider session receives
77
+ * on its first turn, from the session's persisted transcript. Selection
78
+ * walks from the newest message backwards under `maxChars`; the oldest kept
79
+ * entry may be truncated from its front. Returns undefined when no message
80
+ * renders any content. Defaults present the block as a fork; a restored
81
+ * session passes the RESTORED_SESSION_CONTEXT_* values.
82
+ */
83
+ function buildForkContextBlock(messages, options) {
84
+ const maxChars = options?.maxChars ?? MAX_FORK_CONTEXT_CHARS;
85
+ const preamble = options?.preamble ?? FORK_CONTEXT_PREAMBLE;
86
+ const tag = options?.tag ?? FORK_CONTEXT_TAG;
87
+ const formatted = messages.map(formatForkContextMessage).filter(Boolean);
88
+ if (!formatted.length) return void 0;
89
+ const selected = [];
90
+ let total = 0;
91
+ for (const entry of formatted.reverse()) {
92
+ const length = entry.length + 2;
93
+ if (total + length > maxChars && selected.length) break;
94
+ selected.push(total + length > maxChars ? entry.slice(-(maxChars - total)) : entry);
95
+ total += Math.min(length, maxChars - total);
96
+ if (total >= maxChars) break;
97
+ }
98
+ return [
99
+ preamble,
100
+ "",
101
+ `<${tag}>`,
102
+ ...selected.reverse(),
103
+ `</${tag}>`
104
+ ].join("\n");
105
+ }
106
+ /** Refuse an incomplete replay when a native session must carry exact history. */
107
+ function buildCompleteForkContextBlock(messages, options) {
108
+ if (messages.length === 0) return void 0;
109
+ const tag = options?.tag ?? FORK_CONTEXT_TAG;
110
+ const complete = [
111
+ options?.preamble ?? FORK_CONTEXT_PREAMBLE,
112
+ "",
113
+ `<${tag}>`,
114
+ ...messages.map((message) => `${message.role}:\n${JSON.stringify(message.parts)}`),
115
+ `</${tag}>`
116
+ ].join("\n");
117
+ if (complete.length > (options?.maxChars ?? MAX_FORK_CONTEXT_CHARS)) throw new Error("Complete conversation history exceeds the native replay limit");
118
+ return complete;
119
+ }
120
+ /**
121
+ * Forks a session along with its messages up to and including
122
+ * `options.messageId` (all messages when absent). A failed copy deletes the
123
+ * forked session and its partial messages before rethrowing.
124
+ */
125
+ async function forkSessionWithMessages(sessionStore, messageStore, sessionId, options) {
126
+ const forkedSession = await sessionStore.fork(sessionId, options);
127
+ try {
128
+ const messagesToCopy = await messageStore.list(sessionId, { through: options?.messageId });
129
+ for (const message of messagesToCopy) await messageStore.append({
130
+ sessionId: forkedSession.id,
131
+ role: message.role,
132
+ parts: message.parts,
133
+ tokenUsage: message.tokenUsage,
134
+ metadata: message.metadata
135
+ });
136
+ return {
137
+ session: forkedSession,
138
+ messagesCopied: messagesToCopy.length
139
+ };
140
+ } catch (error) {
141
+ const cleanupErrors = [];
142
+ try {
143
+ await messageStore.clear(forkedSession.id);
144
+ } catch (cleanupError) {
145
+ cleanupErrors.push(cleanupError);
146
+ }
147
+ try {
148
+ if (!await sessionStore.delete(forkedSession.id)) cleanupErrors.push(/* @__PURE__ */ new Error(`Forked session was not deleted: ${forkedSession.id}`));
149
+ } catch (cleanupError) {
150
+ cleanupErrors.push(cleanupError);
151
+ }
152
+ if (cleanupErrors.length > 0) throw new AggregateError([error, ...cleanupErrors], `Failed to copy messages and clean up forked session ${forkedSession.id}`);
153
+ throw error;
154
+ }
155
+ }
156
+ //#endregion
157
+ //#region src/message-ids.ts
158
+ /**
159
+ * Derive the two message identifiers owned by one execution.
160
+ *
161
+ * Sidecar executions use their execution id as the assistant message id.
162
+ * The user message uses the same id with a role suffix, so retries overwrite
163
+ * one record instead of adding a second index entry.
164
+ */
165
+ function providerMessageIdsForExecution(executionId) {
166
+ if (!executionId) return void 0;
167
+ return {
168
+ userMessageId: `${executionId}-user`,
169
+ assistantMessageId: executionId
170
+ };
171
+ }
172
+ /**
173
+ * Read the internal provider-message identity carried through the adapter
174
+ * input by the sidecar. Public AgentExecutionInput intentionally stays
175
+ * unchanged; this is a private cross-package transport field.
176
+ */
177
+ function readProviderMessageIds(input) {
178
+ return input.providerMessageIds;
179
+ }
180
+ //#endregion
181
+ //#region src/file-storage.ts
182
+ /**
183
+ * Returns a store identifier that is safe as one path segment, or throws.
184
+ * Sessions and messages share it: every session id also names a message
185
+ * directory.
186
+ */
187
+ function storageId(value) {
188
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) throw new Error("Storage identifier is not canonical");
189
+ return value;
190
+ }
191
+ function isMissing(error) {
192
+ return error.code === "ENOENT";
193
+ }
194
+ /** Parses a JSON file; a missing file reads as null. */
195
+ async function readJsonFile(filePath) {
196
+ try {
197
+ return JSON.parse(await fs$1.readFile(filePath, "utf-8"));
198
+ } catch (error) {
199
+ if (isMissing(error)) return null;
200
+ throw error;
201
+ }
202
+ }
203
+ /**
204
+ * Durably replaces a pretty-printed JSON file, creating parent directories.
205
+ * The store may live in a workspace another uid reads.
206
+ */
207
+ async function writeJsonFile(filePath, data) {
208
+ await fs$1.mkdir(path.dirname(filePath), { recursive: true });
209
+ await writeFileDurably(filePath, JSON.stringify(data, null, 2), { mode: 420 });
210
+ }
211
+ /** Deletes a file; true when it existed. */
212
+ async function deleteFile(filePath) {
213
+ try {
214
+ await fs$1.unlink(filePath);
215
+ return true;
216
+ } catch (error) {
217
+ if (isMissing(error)) return false;
218
+ throw error;
219
+ }
220
+ }
221
+ /** Whether a path exists, without following a final symlink. */
222
+ async function pathExists(targetPath) {
223
+ try {
224
+ await fs$1.lstat(targetPath);
225
+ return true;
226
+ } catch (error) {
227
+ if (isMissing(error)) return false;
228
+ throw error;
229
+ }
230
+ }
231
+ /** Lists a directory's files; a missing directory lists as empty. */
232
+ async function listFiles(dirPath) {
233
+ try {
234
+ return (await fs$1.readdir(dirPath, { withFileTypes: true })).filter((e) => e.isFile()).map((e) => e.name);
235
+ } catch (error) {
236
+ if (isMissing(error)) return [];
237
+ throw error;
238
+ }
239
+ }
240
+ //#endregion
241
+ //#region src/message-store.ts
242
+ /**
243
+ * Creates a file-based message store. Each session keeps one JSON file per
244
+ * message plus `_index.json`, which owns message order.
245
+ */
246
+ function createMessageStore(config) {
247
+ const messagesDir = (sessionId) => path.join(config.storagePath, config.storageDir, "messages", storageId(sessionId));
248
+ const messagePath = (sessionId, messageId) => path.join(messagesDir(sessionId), `${storageId(messageId)}.json`);
249
+ const indexPath = (sessionId) => path.join(messagesDir(sessionId), "_index.json");
250
+ async function getIndex(sessionId, requireComplete = false, allowAbsent = false) {
251
+ const index = await readJsonFile(indexPath(sessionId));
252
+ if (requireComplete && index === null) {
253
+ if (allowAbsent && !await pathExists(messagesDir(sessionId))) return [];
254
+ throw new Error("Complete message history index is missing");
255
+ }
256
+ if (index !== null && (!Array.isArray(index) || index.some((id) => typeof id !== "string" || storageId(id) !== id))) throw new Error("Message history index is invalid");
257
+ if (requireComplete && index && new Set(index).size !== index.length) throw new Error("Complete message history index has duplicate IDs");
258
+ return index ?? [];
259
+ }
260
+ return {
261
+ async append(options) {
262
+ const message = {
263
+ id: options.id ?? randomUUID(),
264
+ sessionId: options.sessionId,
265
+ role: options.role,
266
+ parts: options.parts,
267
+ timestamp: options.timestamp ?? /* @__PURE__ */ new Date(),
268
+ tokenUsage: options.tokenUsage,
269
+ metadata: options.metadata
270
+ };
271
+ await writeJsonFile(messagePath(options.sessionId, message.id), {
272
+ ...message,
273
+ timestamp: message.timestamp.toISOString()
274
+ });
275
+ const index = await getIndex(options.sessionId);
276
+ if (!index.includes(message.id)) index.push(message.id);
277
+ await writeJsonFile(indexPath(options.sessionId), index);
278
+ return message;
279
+ },
280
+ async list(sessionId, options) {
281
+ const index = await getIndex(sessionId, options?.requireComplete, options?.allowAbsent);
282
+ let end = index.length;
283
+ if (options?.through) {
284
+ end = index.indexOf(options.through) + 1;
285
+ if (end === 0) throw new Error(`Message not found: ${options.through}`);
286
+ }
287
+ const offset = options?.offset ?? 0;
288
+ const messageIds = index.slice(offset, options?.limit ? Math.min(end, offset + options.limit) : end);
289
+ const messages = [];
290
+ for (const messageId of messageIds) {
291
+ const data = await readJsonFile(messagePath(sessionId, messageId));
292
+ if (!data) {
293
+ if (options?.requireComplete) throw new Error("Complete message history has a missing message");
294
+ continue;
295
+ }
296
+ if (options?.requireComplete && (data.id !== messageId || data.sessionId !== sessionId)) throw new Error("Complete message history record identity differs from its index");
297
+ const message = {
298
+ ...data,
299
+ timestamp: new Date(data.timestamp)
300
+ };
301
+ messages.push(message);
302
+ }
303
+ return messages;
304
+ },
305
+ async clear(sessionId) {
306
+ await fs$1.rm(messagesDir(sessionId), {
307
+ recursive: true,
308
+ force: true
309
+ });
310
+ },
311
+ async initialize(sessionId) {
312
+ if (await readJsonFile(indexPath(sessionId)) !== null) {
313
+ await getIndex(sessionId, true);
314
+ return;
315
+ }
316
+ if (await pathExists(messagesDir(sessionId))) throw new Error("Message history directory has no complete index");
317
+ await writeJsonFile(indexPath(sessionId), []);
318
+ }
319
+ };
320
+ }
321
+ //#endregion
322
+ //#region src/session-store.ts
323
+ function serializeSession(session) {
324
+ return {
325
+ ...session,
326
+ createdAt: session.createdAt.toISOString(),
327
+ lastAccessedAt: session.lastAccessedAt.toISOString()
328
+ };
329
+ }
330
+ function deserializeSession(data) {
331
+ return {
332
+ ...data,
333
+ createdAt: new Date(data.createdAt),
334
+ lastAccessedAt: new Date(data.lastAccessedAt)
335
+ };
336
+ }
337
+ /**
338
+ * Creates a file-based session store.
339
+ */
340
+ function createSessionStore(config) {
341
+ const sessionsDir = path.join(config.storagePath, config.storageDir, "sessions");
342
+ function getSessionPath(sessionId) {
343
+ return path.join(sessionsDir, `${storageId(sessionId)}.json`);
344
+ }
345
+ async function read(sessionId) {
346
+ const data = await readJsonFile(getSessionPath(sessionId));
347
+ return data && deserializeSession(data);
348
+ }
349
+ async function write(session) {
350
+ await writeJsonFile(getSessionPath(session.id), serializeSession(session));
351
+ }
352
+ return {
353
+ async create(options) {
354
+ const now = /* @__PURE__ */ new Date();
355
+ const session = {
356
+ id: options.id ?? randomUUID(),
357
+ workspaceRoot: options.workspaceRoot,
358
+ providerSessionId: options.providerSessionId,
359
+ providerSessionHome: options.providerSessionHome,
360
+ createdAt: now,
361
+ lastAccessedAt: now
362
+ };
363
+ await write(session);
364
+ return session;
365
+ },
366
+ get: read,
367
+ async update(sessionId, updates) {
368
+ const session = await read(sessionId);
369
+ if (!session) return null;
370
+ const updated = {
371
+ ...session,
372
+ ...updates,
373
+ lastAccessedAt: /* @__PURE__ */ new Date()
374
+ };
375
+ await write(updated);
376
+ return updated;
377
+ },
378
+ async delete(sessionId) {
379
+ return deleteFile(getSessionPath(sessionId));
380
+ },
381
+ async list(options) {
382
+ const sessions = [];
383
+ for (const file of await listFiles(sessionsDir)) {
384
+ if (!file.endsWith(".json")) continue;
385
+ const data = await readJsonFile(path.join(sessionsDir, file));
386
+ if (!data) continue;
387
+ if (options?.workspaceRoot && data.workspaceRoot !== options.workspaceRoot) continue;
388
+ sessions.push(deserializeSession(data));
389
+ }
390
+ return sessions;
391
+ },
392
+ async fork(sessionId, options) {
393
+ const parent = await read(sessionId);
394
+ if (!parent) throw new Error(`Session not found: ${sessionId}`);
395
+ if (options?.id && await read(options.id)) throw new Error(`Cannot fork into session id ${options.id}: a session with that id already exists`);
396
+ const now = /* @__PURE__ */ new Date();
397
+ const forked = {
398
+ id: options?.id ?? randomUUID(),
399
+ parentId: sessionId,
400
+ forkMessageId: options?.messageId,
401
+ workspaceRoot: options?.workspaceRoot ?? parent.workspaceRoot,
402
+ createdAt: now,
403
+ lastAccessedAt: now
404
+ };
405
+ await write(forked);
406
+ return forked;
407
+ }
408
+ };
409
+ }
410
+ //#endregion
411
+ export { DURABLE_FILE_MODE, MAX_SECRET_PROFILE_REPLAY_CHARS, RESTORED_SESSION_CONTEXT_PREAMBLE, RESTORED_SESSION_CONTEXT_TAG, buildCompleteForkContextBlock, buildForkContextBlock, createMessageStore, createSessionStore, forkSessionWithMessages, providerMessageIdsForExecution, readProviderMessageIds, syncDirectory, temporarySibling, writeFileDurably };
412
+
413
+ //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-session-persistence",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.7.1",
4
+ "description": "File-based session and message storage for CLI providers without built-in persistence",
5
+ "type": "module",
6
+ "main": "./dist/index.mjs",
7
+ "types": "./dist/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "!dist/**/*.map"
17
+ ],
18
+ "dependencies": {
19
+ "@tangle-network/agent-interface": "^5.10.13"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "25.6.0",
23
+ "tsdown": "0.21.10",
24
+ "typescript": "^6.0.3",
25
+ "vitest": "^4.1.12"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org"
30
+ },
31
+ "tangleRelease": {
32
+ "sourceSha": "4f0c9345ec23e3dd680cc869ca18da47afd0af48",
33
+ "mergedAt": "2026-11-02T07:39:16-08:00"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown",
37
+ "check-types": "node ../../scripts/tsc-native.mjs --noEmit",
38
+ "test": "vitest run",
39
+ "test:watch": "vitest"
40
+ }
6
41
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.