@crowgentai/emo-session 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @crowgentai/emo-session
2
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.
3
+ A durable, append-only session journal. Every message and event is written as one
4
+ NDJSON line and `fsync`ed, so a crash loses nothing that was already acknowledged.
5
+
6
+ ```bash
7
+ npm install @crowgentai/emo-session
8
+ ```
9
+
10
+ ```ts
11
+ import { Session } from "@crowgentai/emo-session";
12
+
13
+ const session = await Session.create("/state", { cwd, provider: "openai", model: "gpt-4o-mini" });
14
+ await session.appendMessage({ role: "user", content: "hello" });
15
+ await session.appendMessage({ role: "assistant", content: "hi" });
16
+ await session.setTodos(["write tests"]);
17
+ await session.finish("done");
18
+
19
+ const reopened = await Session.load("/state", session.id);
20
+ reopened.messages; // the whole conversation, replayed from the journal
21
+ reopened.todos; // last todo snapshot
22
+ ```
23
+
24
+ Sessions live under `<stateDir>/sessions/<id>/`:
25
+
26
+ ```
27
+ sessions/s_9f3c/
28
+ ├── meta.json # id, timestamps, cwd, provider, model, title, status
29
+ └── journal.ndjson # one JSON object per line: { seq, ts, type, data }
30
+ ```
31
+
32
+ Entry types: `session_start`, `message`, `event`, `error`, `todo`.
33
+
34
+ See [docs/api.md](docs/api.md) for the full class and recovery semantics.
@@ -0,0 +1,2 @@
1
+ export * from "./session.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./session.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC"}
@@ -0,0 +1,34 @@
1
+ import type { ChatMessage, JournalEntryType, SessionMeta } from "@crowgentai/emo-core";
2
+ export declare class Session {
3
+ readonly dir: string;
4
+ readonly meta: SessionMeta;
5
+ readonly messages: ChatMessage[];
6
+ readonly todos: string[];
7
+ private seq;
8
+ private handle;
9
+ private constructor();
10
+ get id(): string;
11
+ private get journalPath();
12
+ static create(stateDir: string, opts: {
13
+ cwd: string;
14
+ provider: string;
15
+ model: string;
16
+ title?: string;
17
+ }): Promise<Session>;
18
+ static load(stateDir: string, id: string): Promise<Session>;
19
+ private static createWithEntries;
20
+ static clone(stateDir: string, id: string): Promise<Session>;
21
+ static fork(stateDir: string, id: string, upToUserMessage?: number): Promise<Session>;
22
+ static exportJsonl(stateDir: string, id: string): Promise<string>;
23
+ static exportJson(stateDir: string, id: string): Promise<string>;
24
+ static list(stateDir: string): Promise<SessionMeta[]>;
25
+ private touch;
26
+ append(type: JournalEntryType, data: unknown): Promise<void>;
27
+ appendMessage(message: ChatMessage): Promise<void>;
28
+ setTitle(title: string): Promise<void>;
29
+ setTodos(items: string[]): Promise<void>;
30
+ setStatus(status: SessionMeta["status"]): Promise<void>;
31
+ finish(status: SessionMeta["status"]): Promise<void>;
32
+ close(): Promise<void>;
33
+ }
34
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAgB,gBAAgB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAmBrG,qBAAa,OAAO;IAKhB,QAAQ,CAAC,GAAG,EAAE,MAAM;IACpB,QAAQ,CAAC,IAAI,EAAE,WAAW;IAC1B,QAAQ,CAAC,QAAQ,EAAE,WAAW,EAAE;IAChC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE;IAP1B,OAAO,CAAC,GAAG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;IAMxC,SAAS,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAMpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAM7B"}
@@ -0,0 +1,211 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { open } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { readJson, writeJson } from "@crowgentai/emo-core";
5
+ import { newId, nowIso } from "@crowgentai/emo-core";
6
+ const SESSIONS_DIR = "sessions";
7
+ async function readJournal(file) {
8
+ try {
9
+ const raw = await fs.readFile(file, "utf8");
10
+ return raw
11
+ .split("\n")
12
+ .filter((line) => line.trim().length > 0)
13
+ .map((line) => JSON.parse(line));
14
+ }
15
+ catch (err) {
16
+ if (err.code === "ENOENT")
17
+ return [];
18
+ throw err;
19
+ }
20
+ }
21
+ export class Session {
22
+ dir;
23
+ meta;
24
+ messages;
25
+ todos;
26
+ seq = 0;
27
+ handle = null;
28
+ constructor(dir, meta, messages, todos) {
29
+ this.dir = dir;
30
+ this.meta = meta;
31
+ this.messages = messages;
32
+ this.todos = todos;
33
+ }
34
+ get id() {
35
+ return this.meta.id;
36
+ }
37
+ get journalPath() {
38
+ return path.join(this.dir, "journal.ndjson");
39
+ }
40
+ static async create(stateDir, opts) {
41
+ const id = newId("s_");
42
+ const dir = path.join(stateDir, SESSIONS_DIR, id);
43
+ await fs.mkdir(dir, { recursive: true });
44
+ const meta = {
45
+ id,
46
+ createdAt: nowIso(),
47
+ updatedAt: nowIso(),
48
+ cwd: opts.cwd,
49
+ provider: opts.provider,
50
+ model: opts.model,
51
+ title: opts.title ?? "",
52
+ status: "running",
53
+ };
54
+ await writeJson(path.join(dir, "meta.json"), meta);
55
+ const session = new Session(dir, meta, [], []);
56
+ session.handle = await open(session.journalPath, "a");
57
+ await session.append("session_start", { cwd: opts.cwd, provider: opts.provider, model: opts.model });
58
+ return session;
59
+ }
60
+ static async load(stateDir, id) {
61
+ const dir = path.join(stateDir, SESSIONS_DIR, id);
62
+ const meta = await readJson(path.join(dir, "meta.json"), null);
63
+ if (!meta)
64
+ throw new Error(`session not found: ${id}`);
65
+ const entries = await readJournal(path.join(dir, "journal.ndjson"));
66
+ const messages = entries.filter((entry) => entry.type === "message").map((entry) => entry.data);
67
+ const todos = entries
68
+ .filter((entry) => entry.type === "todo" && Array.isArray(entry.data))
69
+ .map((entry) => entry.data.map(String))
70
+ .pop() ?? [];
71
+ const session = new Session(dir, meta, messages, todos);
72
+ session.seq = entries.length > 0 ? entries[entries.length - 1].seq : 0;
73
+ session.handle = await open(session.journalPath, "a");
74
+ session.meta.status = "running";
75
+ await session.touch();
76
+ return session;
77
+ }
78
+ static async createWithEntries(stateDir, opts, entries) {
79
+ const id = newId("s_");
80
+ const dir = path.join(stateDir, SESSIONS_DIR, id);
81
+ await fs.mkdir(dir, { recursive: true });
82
+ const meta = {
83
+ id,
84
+ createdAt: nowIso(),
85
+ updatedAt: nowIso(),
86
+ cwd: opts.cwd,
87
+ provider: opts.provider,
88
+ model: opts.model,
89
+ title: opts.title ?? "",
90
+ status: "running",
91
+ forkedFrom: opts.forkedFrom,
92
+ };
93
+ await writeJson(path.join(dir, "meta.json"), meta);
94
+ const messages = entries.filter((entry) => entry.type === "message").map((entry) => entry.data);
95
+ const todos = entries
96
+ .filter((entry) => entry.type === "todo" && Array.isArray(entry.data))
97
+ .map((entry) => entry.data.map(String))
98
+ .pop() ?? [];
99
+ const session = new Session(dir, meta, messages, todos);
100
+ session.handle = await open(path.join(dir, "journal.ndjson"), "a");
101
+ session.seq = entries.length > 0 ? entries[entries.length - 1].seq : 0;
102
+ for (const entry of entries) {
103
+ await session.handle.write(`${JSON.stringify(entry)}\n`);
104
+ }
105
+ await session.handle.sync();
106
+ return session;
107
+ }
108
+ static async clone(stateDir, id) {
109
+ const source = await Session.load(stateDir, id);
110
+ const entries = await readJournal(path.join(source.dir, "journal.ndjson"));
111
+ const title = source.meta.title ? `${source.meta.title} (copy)` : "";
112
+ await source.close();
113
+ return Session.createWithEntries(stateDir, { cwd: source.meta.cwd, provider: source.meta.provider, model: source.meta.model, title, forkedFrom: id }, entries);
114
+ }
115
+ static async fork(stateDir, id, upToUserMessage = Number.POSITIVE_INFINITY) {
116
+ const source = await Session.load(stateDir, id);
117
+ const entries = await readJournal(path.join(source.dir, "journal.ndjson"));
118
+ const userIndexes = entries
119
+ .map((entry, index) => ({ entry, index }))
120
+ .filter(({ entry }) => entry.type === "message" && entry.data.role === "user")
121
+ .map(({ index }) => index);
122
+ const cut = userIndexes.length === 0 ? entries.length : (userIndexes[Math.min(upToUserMessage - 1, userIndexes.length - 1)] ?? entries.length - 1);
123
+ const kept = entries.slice(0, cut + 1);
124
+ const forkEntry = {
125
+ seq: kept.length > 0 ? kept[kept.length - 1].seq + 1 : 1,
126
+ ts: nowIso(),
127
+ type: "fork",
128
+ data: { from: id, userMessage: Math.min(upToUserMessage, userIndexes.length) },
129
+ };
130
+ await source.close();
131
+ return Session.createWithEntries(stateDir, { cwd: source.meta.cwd, provider: source.meta.provider, model: source.meta.model, title: source.meta.title, forkedFrom: id }, [...kept, forkEntry]);
132
+ }
133
+ static async exportJsonl(stateDir, id) {
134
+ const dir = path.join(stateDir, SESSIONS_DIR, id);
135
+ const meta = await readJson(path.join(dir, "meta.json"), null);
136
+ if (!meta)
137
+ throw new Error(`session not found: ${id}`);
138
+ return fs.readFile(path.join(dir, "journal.ndjson"), "utf8");
139
+ }
140
+ static async exportJson(stateDir, id) {
141
+ const dir = path.join(stateDir, SESSIONS_DIR, id);
142
+ const meta = await readJson(path.join(dir, "meta.json"), null);
143
+ if (!meta)
144
+ throw new Error(`session not found: ${id}`);
145
+ const entries = await readJournal(path.join(dir, "journal.ndjson"));
146
+ return JSON.stringify({ meta, entries }, null, 2);
147
+ }
148
+ static async list(stateDir) {
149
+ const root = path.join(stateDir, SESSIONS_DIR);
150
+ let names = [];
151
+ try {
152
+ names = await fs.readdir(root);
153
+ }
154
+ catch (err) {
155
+ if (err.code === "ENOENT")
156
+ return [];
157
+ throw err;
158
+ }
159
+ const metas = [];
160
+ for (const name of names) {
161
+ const meta = await readJson(path.join(root, name, "meta.json"), null);
162
+ if (meta)
163
+ metas.push(meta);
164
+ }
165
+ return metas.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
166
+ }
167
+ async touch() {
168
+ this.meta.updatedAt = nowIso();
169
+ await writeJson(path.join(this.dir, "meta.json"), this.meta);
170
+ }
171
+ async append(type, data) {
172
+ if (!this.handle)
173
+ return;
174
+ this.seq += 1;
175
+ const entry = { seq: this.seq, ts: nowIso(), type, data };
176
+ await this.handle.write(`${JSON.stringify(entry)}\n`);
177
+ await this.handle.sync();
178
+ }
179
+ async appendMessage(message) {
180
+ this.messages.push(message);
181
+ await this.append("message", message);
182
+ await this.touch();
183
+ }
184
+ async setTitle(title) {
185
+ if (!title || this.meta.title)
186
+ return;
187
+ this.meta.title = title.slice(0, 80);
188
+ await this.touch();
189
+ }
190
+ async setTodos(items) {
191
+ this.todos.splice(0, this.todos.length, ...items);
192
+ await this.append("todo", items);
193
+ await this.touch();
194
+ }
195
+ async setStatus(status) {
196
+ this.meta.status = status;
197
+ await this.touch();
198
+ }
199
+ async finish(status) {
200
+ this.meta.status = status;
201
+ await this.touch();
202
+ await this.close();
203
+ }
204
+ async close() {
205
+ if (this.handle) {
206
+ await this.handle.close();
207
+ this.handle = null;
208
+ }
209
+ }
210
+ }
211
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAExC,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,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EAAE,EAAE,CAAC,CAAC;QACrC,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,KAAe;QAC5B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC;QAClD,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACjC,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,MAA6B;QAC3C,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAC1B,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,MAA6B;QACxC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAC1B,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACnB,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACrB,CAAC;IACH,CAAC;CACF"}
package/docs/api.md ADDED
@@ -0,0 +1,71 @@
1
+ # @crowgentai/emo-session API
2
+
3
+ ## Creating and loading
4
+
5
+ ```ts
6
+ import { Session } from "@crowgentai/emo-session";
7
+
8
+ const session = await Session.create(stateDir, {
9
+ cwd: "/work/app",
10
+ provider: "openai",
11
+ model: "gpt-4o-mini",
12
+ title: "fix the tests", // optional; the first user message is used otherwise
13
+ });
14
+
15
+ const resumed = await Session.load(stateDir, "s_abc123");
16
+ const all = await Session.list(stateDir); // SessionMeta[], newest first
17
+ ```
18
+
19
+ `load()` replays the journal: `messages` are every entry of type `message`, `todos` is the
20
+ last `todo` entry, and the sequence counter resumes from the last entry. Loading sets the
21
+ status back to `running` because the session is live again.
22
+
23
+ ## Fork, clone and export
24
+
25
+ ```ts
26
+ const forked = await Session.fork(stateDir, "s_abc123", 2); // copy history up to user message 2
27
+ const copied = await Session.clone(stateDir, "s_abc123"); // copy the whole journal
28
+ await Session.exportJsonl(stateDir, "s_abc123"); // the journal as NDJSON text
29
+ await Session.exportJson(stateDir, "s_abc123"); // { meta, entries } as JSON
30
+ ```
31
+
32
+ Forking keeps every entry up to the chosen user message and appends a `fork` entry
33
+ recording the source session; the new session's `meta.forkedFrom` names it. Cloning copies
34
+ the whole journal. CLI: `emo fork <id> [n]`, `emo clone <id>`,
35
+ `emo export <id> [--format json|jsonl] [--out file]`.
36
+
37
+ ## Writing
38
+
39
+ ```ts
40
+ await session.appendMessage({ role: "user", content: "hello" });
41
+ await session.append("event", { kind: "compaction" }); // custom journal entry
42
+ await session.setTodos(["one", "two"]);
43
+ await session.setTitle("a short title"); // ignored once a title exists
44
+ await session.setStatus("error");
45
+ ```
46
+
47
+ `appendMessage()` also updates `meta.updatedAt` on disk. Each write is followed by
48
+ `handle.sync()`, so a power loss cannot reorder or drop acknowledged entries.
49
+
50
+ ## Finishing
51
+
52
+ ```ts
53
+ await session.finish("done"); // "running" | "done" | "error"; closes the journal
54
+ await session.close(); // close without changing the status
55
+ ```
56
+
57
+ ## Properties
58
+
59
+ | Name | Type | Notes |
60
+ | --- | --- | --- |
61
+ | `id` | `string` | `s_` prefixed |
62
+ | `dir` | `string` | session directory |
63
+ | `meta` | `SessionMeta` | mutable in memory, persisted on change |
64
+ | `messages` | `ChatMessage[]` | live conversation |
65
+ | `todos` | `string[]` | last persisted task list |
66
+
67
+ ## Crash recovery
68
+
69
+ The journal is the source of truth; `meta.json` is a cache of timestamps, title and
70
+ status. If `meta.json` is lost, the journal still replays the conversation — but
71
+ `Session.load` needs the metadata file, so keep the two together in the session dir.
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@crowgentai/emo-session",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Durable, append-only session journal that survives crashes and resumes exactly.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/crowgent/emo.git",
10
+ "directory": "packages/session"
11
+ },
12
+ "homepage": "https://github.com/crowgent/emo#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/crowgent/emo/issues"
15
+ },
16
+ "keywords": [
17
+ "agent",
18
+ "ai",
19
+ "llm",
20
+ "emo",
21
+ "session"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "docs"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.json",
44
+ "typecheck": "tsc -p tsconfig.json --noEmit",
45
+ "test": "node --import tsx --test \"test/*.test.ts\"",
46
+ "prepublishOnly": "npm run build"
47
+ },
48
+ "dependencies": {
49
+ "@crowgentai/emo-core": "^0.1.0"
50
+ }
51
+ }