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

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