agentfootprint 7.27.1 → 7.28.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.
@@ -0,0 +1,376 @@
1
+ "use strict";
2
+ /**
3
+ * hosting/sqliteSessions — conversations in a file, so a restart is not an
4
+ * amnesia event.
5
+ *
6
+ * `memorySessions()` keeps conversations in a `Map` and says what that costs in
7
+ * its own docstring: restart the process and every conversation is gone. Until
8
+ * now the next step up was "bring a Redis", and the step between those two —
9
+ * *one machine, one file, nothing to install* — was a store every consumer had
10
+ * to write for themselves. This is that store.
11
+ *
12
+ * A paused run was in the same position from the other direction. `agent.run()`
13
+ * hands back a checkpoint that is documented as JSON you can keep anywhere, and
14
+ * "anywhere" was the whole of the offer: the library named a shape and left the
15
+ * keeping to you. Both halves land in the same table here, because
16
+ * {@link CheckpointEnvelope} was already a union of the two and a session store
17
+ * has no business caring which one it is holding.
18
+ *
19
+ * ── What this is, said plainly ──────────────────────────────────────────────
20
+ * **One process on one machine, writing one file.** That is the whole claim,
21
+ * and it is worth stating as a ceiling rather than leaving it to be discovered:
22
+ *
23
+ * • It survives a restart, a crash, a deploy — anything that ends the process
24
+ * and leaves the disk alone.
25
+ * • It is NOT a distributed store. Two machines do not share a session by
26
+ * both opening this file over a network filesystem, and nothing here tries
27
+ * to make that work.
28
+ * • WAL lets readers and one writer run at once, and **one writer at a time
29
+ * is the ceiling** — a second writer waits for the lock up to
30
+ * `busyTimeoutMs` and then fails loudly rather than queueing forever.
31
+ * Several processes on one box is fine at that scale; a fleet is not what
32
+ * this is.
33
+ *
34
+ * When you outgrow it you swap the one argument to `standingAgent`, which is
35
+ * the entire point of the port.
36
+ *
37
+ * ── Zero dependencies, and the version floor that buys ──────────────────────
38
+ * SQLite is *inside Node* — `node:sqlite`, no install, no native build, no
39
+ * peer dependency. The price is a version floor this package does not otherwise
40
+ * have: the module ships with Node 22.5 and newer. Rather than raise `engines`
41
+ * for one optional adapter and break every consumer on Node 20, the module is
42
+ * loaded when you actually construct a store, and its absence is refused by
43
+ * name with the version you are on and what to do about it — see
44
+ * {@link SqliteUnavailableError}. There is deliberately **no fallback to
45
+ * memory**: a store that silently forgot everything on restart is
46
+ * indistinguishable, from the outside, from a brand-new user.
47
+ *
48
+ * ── The two laws it inherits rather than re-implements ──────────────────────
49
+ * `checkEnvelope` is called on the way out AND on the way in, so an envelope
50
+ * whose `format` this runtime does not know is refused by name, and a stored
51
+ * session that is PRESENT but unreadable is refused by name too. Only a session
52
+ * that was never written hydrates as `undefined`. Validating on the way in as
53
+ * well is the cheap half of that promise: a row this store could not read back
54
+ * never gets written in the first place.
55
+ */
56
+ Object.defineProperty(exports, "__esModule", { value: true });
57
+ exports.sqliteSessions = exports.UnreadableSessionFileError = exports.SqliteUnavailableError = void 0;
58
+ const envelope_js_1 = require("./envelope.js");
59
+ const errors_js_1 = require("./errors.js");
60
+ const lazyRequire_js_1 = require("../lib/lazyRequire.js");
61
+ // ─── The refusals ────────────────────────────────────────────────────
62
+ /**
63
+ * Raised when `node:sqlite` is not available in the running Node.
64
+ *
65
+ * Node 20 does not have the module at all; Node 22.5 through 22.12 have it
66
+ * behind `--experimental-sqlite`; Node 22.13+ and 23.4+ have it as-is (still
67
+ * marked experimental by Node, which is why it prints a warning on first use).
68
+ *
69
+ * The refusal names the version you are on and the three ways out, because
70
+ * "cannot find module 'node:sqlite'" out of a library's guts tells you what
71
+ * broke and nothing about what to do.
72
+ */
73
+ class SqliteUnavailableError extends Error {
74
+ code = 'ERR_SQLITE_UNAVAILABLE';
75
+ /** The Node version this process is running. */
76
+ nodeVersion;
77
+ constructor(nodeVersion, reason) {
78
+ super(`[hosting] sqliteSessions() needs Node's built-in 'node:sqlite' module, and this ` +
79
+ `process (Node ${nodeVersion}) does not have it (${reason}). ` +
80
+ `That module ships with Node 22.5 and newer: on Node 22.13+ (and 23.4+) it is ` +
81
+ `available as-is, and on Node 22.5–22.12 it is behind --experimental-sqlite. ` +
82
+ `So: upgrade Node, add that flag, or use memorySessions() — which keeps ` +
83
+ `conversations in a Map and loses them on restart, and says so in its name. ` +
84
+ `This refuses rather than falling back to memory on your behalf: a store that ` +
85
+ `silently forgot every conversation on restart looks, from the outside, exactly ` +
86
+ `like a brand-new user.`);
87
+ this.name = 'SqliteUnavailableError';
88
+ this.nodeVersion = nodeVersion;
89
+ }
90
+ }
91
+ exports.SqliteUnavailableError = SqliteUnavailableError;
92
+ /**
93
+ * Raised when the file exists but this runtime cannot use it as a session
94
+ * store.
95
+ *
96
+ * The same law {@link UnreadableEnvelopeError} states for one stored value,
97
+ * one level up: **an unreadable store and an empty one are different facts, and
98
+ * only one of them is safe to answer with a fresh start.** A store that opened
99
+ * a corrupt file as an empty database would hand every returning user a blank
100
+ * slate and log nothing.
101
+ *
102
+ * `problem` is the fact to branch on — the three cases need different actions:
103
+ *
104
+ * - `'cannot-open'` — not a SQLite database, or not readable (permissions, a
105
+ * directory, a truncated file).
106
+ * - `'not-our-schema'` — a database whose `agent_sessions` table is somebody
107
+ * else's table of that name. Point the store at its own file.
108
+ * - `'newer-schema'` — written by a newer agentfootprint than this one. Same
109
+ * answer the envelope `format` field gives: refuse, never half-read.
110
+ */
111
+ class UnreadableSessionFileError extends Error {
112
+ code = 'ERR_UNREADABLE_SESSION_FILE';
113
+ /** The file that was refused. */
114
+ file;
115
+ /** Which of the three cases this is. */
116
+ problem;
117
+ constructor(file, problem, detail) {
118
+ super(`[hosting] the session store at '${file}' cannot be used: ${detail} ` +
119
+ `An unreadable store and an empty one are different facts, and only one of them ` +
120
+ `is safe to answer with a fresh start — so this refuses rather than quietly ` +
121
+ `beginning every conversation again on top of a file that already exists. ` +
122
+ (problem === 'newer-schema'
123
+ ? `A store written by a newer agentfootprint needs a runtime that knows that ` +
124
+ `schema; roll forward, or point this one at its own file.`
125
+ : problem === 'not-our-schema'
126
+ ? `Give the store a file of its own rather than sharing one with tables of ` +
127
+ `the same name.`
128
+ : `Check the path and its permissions, or move the file aside to start a ` + `new one.`));
129
+ this.name = 'UnreadableSessionFileError';
130
+ this.file = file;
131
+ this.problem = problem;
132
+ }
133
+ }
134
+ exports.UnreadableSessionFileError = UnreadableSessionFileError;
135
+ // ─── The schema ──────────────────────────────────────────────────────
136
+ /**
137
+ * What this runtime writes. Bumped only for a change an older reader could not
138
+ * survive — and an older reader meeting a newer number refuses by name rather
139
+ * than reading what it half-understands, which is the same rule the envelope's
140
+ * `format` field follows.
141
+ */
142
+ const SCHEMA_VERSION = 1;
143
+ const SESSIONS_TABLE = 'agent_sessions';
144
+ const META_TABLE = 'agent_store_meta';
145
+ /**
146
+ * `format` and `saved_at` are COLUMNS as well as fields inside the JSON, and
147
+ * that redundancy is deliberate: it makes the file answer "which sessions are
148
+ * waiting on a person, and since when?" from the `sqlite3` command line during
149
+ * an incident, without a JSON parser and without this library. A store you
150
+ * cannot inspect with the tools already on the box is a store you debug by
151
+ * guessing.
152
+ */
153
+ const SESSIONS_COLUMNS = ['session_id', 'format', 'saved_at', 'envelope'];
154
+ // ─── The store ───────────────────────────────────────────────────────
155
+ /**
156
+ * A session store in one SQLite file — the battery-included place to keep a
157
+ * conversation, or a run that stopped to ask a person something, so that a
158
+ * restart does not lose it.
159
+ *
160
+ * @throws SqliteUnavailableError when the running Node has no `node:sqlite`.
161
+ * @throws UnreadableSessionFileError when the file exists but cannot be used —
162
+ * never answered with an empty store.
163
+ *
164
+ * @example A standing agent whose conversations survive a restart
165
+ * import { standingAgent, nodeHost, sqliteSessions } from 'agentfootprint/hosting';
166
+ *
167
+ * const handle = await standingAgent({
168
+ * agent,
169
+ * sessions: sqliteSessions({ file: './sessions.db' }),
170
+ * host: nodeHost({ port: 8080 }),
171
+ * });
172
+ *
173
+ * @example Keeping a paused run yourself, without the composer
174
+ * const sessions = sqliteSessions({ file: './sessions.db' });
175
+ * const out = await agent.run({ message });
176
+ * if (isPaused(out)) {
177
+ * await sessions.persist(sessionId, toPausedEnvelope({
178
+ * checkpoint: out.checkpoint,
179
+ * conversation: agent.checkpoint()!,
180
+ * pending: { pauseData: out.pauseData },
181
+ * }));
182
+ * }
183
+ * // …a deploy later, in a new process:
184
+ * const paused = readPausedRun(await sessions.hydrate(sessionId));
185
+ * const answer = await agent.resume(paused.checkpoint, decision);
186
+ */
187
+ function sqliteSessions(options) {
188
+ const { file, busyTimeoutMs = 5000 } = options;
189
+ if (file === ':memory:' || file.trim() === '') {
190
+ throw new TypeError(`[hosting] sqliteSessions({ file: '${file}' }) is not a durable store. ` +
191
+ `':memory:' looks like a file and keeps nothing across a restart, which is the ` +
192
+ `one thing this adapter exists to do. Use memorySessions() when an in-process ` +
193
+ `store is what you want — it says so in its name — or give this one a real path.`);
194
+ }
195
+ const DatabaseSync = options._sqlite ?? loadSqlite();
196
+ ensureParentDirectory(file);
197
+ let db;
198
+ try {
199
+ db = new DatabaseSync(file);
200
+ }
201
+ catch (err) {
202
+ throw new UnreadableSessionFileError(file, 'cannot-open', `${describe(err)}.`);
203
+ }
204
+ let journalMode;
205
+ try {
206
+ journalMode = applyPragmas(db, busyTimeoutMs);
207
+ ensureSchema(db, file);
208
+ }
209
+ catch (err) {
210
+ db.close();
211
+ if (err instanceof UnreadableSessionFileError)
212
+ throw err;
213
+ throw new UnreadableSessionFileError(file, 'cannot-open', `${describe(err)}.`);
214
+ }
215
+ const insert = db.prepare(`INSERT INTO ${SESSIONS_TABLE} (session_id, format, saved_at, envelope) VALUES (?, ?, ?, ?) ` +
216
+ `ON CONFLICT(session_id) DO UPDATE SET format = excluded.format, ` +
217
+ `saved_at = excluded.saved_at, envelope = excluded.envelope`);
218
+ const select = db.prepare(`SELECT envelope FROM ${SESSIONS_TABLE} WHERE session_id = ?`);
219
+ const remove = db.prepare(`DELETE FROM ${SESSIONS_TABLE} WHERE session_id = ?`);
220
+ let closed = false;
221
+ const open = (verb) => {
222
+ if (closed) {
223
+ throw new Error(`[hosting] the sqliteSessions store at '${file}' is closed, so it cannot ${verb}. ` +
224
+ `close() is final by design — reopening the file behind you would hide a ` +
225
+ `shutdown-ordering bug rather than surface it. Build a new store if you need ` +
226
+ `one after closing this.`);
227
+ }
228
+ };
229
+ // The three port methods are `async` so that every refusal in them arrives
230
+ // as a REJECTION. A method that returns a promise on the happy path and
231
+ // throws synchronously on the sad one is a method whose callers need two
232
+ // error handlers, and the one they forget is the one that fires at 3am.
233
+ return {
234
+ journalMode,
235
+ // eslint-disable-next-line @typescript-eslint/require-await
236
+ async hydrate(sessionId) {
237
+ open('hydrate a session');
238
+ const row = select.get(sessionId);
239
+ if (row === undefined)
240
+ return undefined;
241
+ const stored = row.envelope;
242
+ if (typeof stored !== 'string') {
243
+ // A row exists and its payload is not even text. Present, unreadable —
244
+ // and specifically NOT `undefined`.
245
+ throw new errors_js_1.UnreadableEnvelopeError(stored, sessionId);
246
+ }
247
+ let parsed;
248
+ try {
249
+ parsed = JSON.parse(stored);
250
+ }
251
+ catch {
252
+ // Bytes written by something that was not this store. Same fact, same
253
+ // refusal: a conversation EXISTS here and this runtime cannot see it.
254
+ throw new errors_js_1.UnreadableEnvelopeError(stored, sessionId);
255
+ }
256
+ // Validate HERE as well as in the composer, so the refusal points at the
257
+ // store that produced the bytes rather than at whoever read them next.
258
+ return (0, envelope_js_1.checkEnvelope)(parsed, sessionId);
259
+ },
260
+ // eslint-disable-next-line @typescript-eslint/require-await
261
+ async persist(sessionId, envelope) {
262
+ open('persist a session');
263
+ // Checked on the way IN as well as out: a row this store could not read
264
+ // back is a row it has no business writing.
265
+ const checked = (0, envelope_js_1.checkEnvelope)(envelope, sessionId);
266
+ insert.run(sessionId, checked.format, checked.savedAt, JSON.stringify(checked));
267
+ },
268
+ // eslint-disable-next-line @typescript-eslint/require-await
269
+ async forget(sessionId) {
270
+ open('forget a session');
271
+ remove.run(sessionId);
272
+ },
273
+ close() {
274
+ if (closed)
275
+ return;
276
+ closed = true;
277
+ db.close();
278
+ },
279
+ };
280
+ }
281
+ exports.sqliteSessions = sqliteSessions;
282
+ // ─── Internals ───────────────────────────────────────────────────────
283
+ /**
284
+ * Load `node:sqlite`, or refuse by name.
285
+ *
286
+ * `lazyRequire` keeps the specifier away from bundler static analysis, so
287
+ * importing `agentfootprint/hosting` costs nothing for the consumers — the vast
288
+ * majority — who never construct one of these.
289
+ */
290
+ function loadSqlite() {
291
+ try {
292
+ const mod = (0, lazyRequire_js_1.lazyRequire)('node:sqlite');
293
+ if (typeof mod?.DatabaseSync !== 'function') {
294
+ throw new Error('the module loaded but has no DatabaseSync');
295
+ }
296
+ return mod.DatabaseSync;
297
+ }
298
+ catch (err) {
299
+ throw new SqliteUnavailableError(nodeVersion(), describe(err));
300
+ }
301
+ }
302
+ /** The version string, without assuming `process` exists. */
303
+ function nodeVersion() {
304
+ return typeof process !== 'undefined' && typeof process.version === 'string'
305
+ ? process.version
306
+ : 'unknown';
307
+ }
308
+ /**
309
+ * Create the file's directory if it is missing — "no infrastructure" should not
310
+ * mean "except for one `mkdir`". A failure here is left to the open call, which
311
+ * reports it with the path in the same words as every other open failure.
312
+ */
313
+ function ensureParentDirectory(file) {
314
+ try {
315
+ const { mkdirSync } = (0, lazyRequire_js_1.lazyRequire)('node:fs');
316
+ const { dirname } = (0, lazyRequire_js_1.lazyRequire)('node:path');
317
+ mkdirSync(dirname(file), { recursive: true });
318
+ }
319
+ catch {
320
+ /* Reported by the open below, with the path and the real reason. */
321
+ }
322
+ }
323
+ /**
324
+ * Set the file up for concurrent use and report what it actually got.
325
+ *
326
+ * `journal_mode` is the first statement executed on purpose: it is the point at
327
+ * which SQLite reads the file header, so "this is not a database" surfaces here,
328
+ * at construction, where the caller can still do something about it — rather
329
+ * than on the first request of the night.
330
+ */
331
+ function applyPragmas(db, busyTimeoutMs) {
332
+ const row = db.prepare('PRAGMA journal_mode = WAL').get();
333
+ // A pragma takes a literal, not a bound parameter, so the number is coerced
334
+ // to one before it reaches the statement rather than trusted to be one.
335
+ const waitMs = Number.isFinite(busyTimeoutMs) ? Math.max(0, Math.floor(busyTimeoutMs)) : 5000;
336
+ db.exec(`PRAGMA busy_timeout = ${waitMs}`);
337
+ // NORMAL, not FULL: with WAL that is durable across a process crash — which
338
+ // is what this store promises — and it does not pay a disk sync per turn.
339
+ // A power cut can still cost the most recent commits; a fleet-grade store is
340
+ // the answer to that, not a pragma.
341
+ db.exec('PRAGMA synchronous = NORMAL');
342
+ return typeof row?.journal_mode === 'string' ? row.journal_mode : 'unknown';
343
+ }
344
+ /** Create the two tables if they are missing, and refuse a file that is not ours. */
345
+ function ensureSchema(db, file) {
346
+ db.exec(`CREATE TABLE IF NOT EXISTS ${SESSIONS_TABLE} (` +
347
+ `session_id TEXT PRIMARY KEY, format TEXT NOT NULL, ` +
348
+ `saved_at INTEGER NOT NULL, envelope TEXT NOT NULL) STRICT`);
349
+ db.exec(`CREATE TABLE IF NOT EXISTS ${META_TABLE} (key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT`);
350
+ // `CREATE TABLE IF NOT EXISTS` succeeds against somebody else's table of the
351
+ // same name, and the failure would otherwise arrive as a confusing constraint
352
+ // error on the first write.
353
+ const columns = db.prepare(`PRAGMA table_info('${SESSIONS_TABLE}')`).all().map((c) => String(c.name));
354
+ const missing = SESSIONS_COLUMNS.filter((name) => !columns.includes(name));
355
+ if (missing.length > 0) {
356
+ throw new UnreadableSessionFileError(file, 'not-our-schema', `it has a '${SESSIONS_TABLE}' table that is not this store's ` +
357
+ `(missing ${missing.join(', ')}; found ${columns.join(', ') || 'nothing'}).`);
358
+ }
359
+ const stored = db
360
+ .prepare(`SELECT value FROM ${META_TABLE} WHERE key = 'schema_version'`)
361
+ .get();
362
+ if (stored === undefined) {
363
+ db.prepare(`INSERT INTO ${META_TABLE} (key, value) VALUES ('schema_version', ?)`).run(String(SCHEMA_VERSION));
364
+ return;
365
+ }
366
+ const found = Number(stored.value);
367
+ if (!Number.isFinite(found) || found > SCHEMA_VERSION) {
368
+ throw new UnreadableSessionFileError(file, 'newer-schema', `it was written with schema version ${String(stored.value)} and this runtime ` +
369
+ `reads version ${SCHEMA_VERSION}.`);
370
+ }
371
+ }
372
+ /** One sentence about a thrown thing, for a message that has to stay readable. */
373
+ function describe(err) {
374
+ return err instanceof Error ? err.message : String(err);
375
+ }
376
+ //# sourceMappingURL=sqliteSessions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqliteSessions.js","sourceRoot":"","sources":["../../src/hosting/sqliteSessions.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;;;AAEH,+CAA8C;AAC9C,2CAAsD;AACtD,0DAAoD;AA2FpD,wEAAwE;AAExE;;;;;;;;;;GAUG;AACH,MAAa,sBAAuB,SAAQ,KAAK;IACtC,IAAI,GAAG,wBAAiC,CAAC;IAClD,gDAAgD;IACvC,WAAW,CAAS;IAE7B,YAAY,WAAmB,EAAE,MAAc;QAC7C,KAAK,CACH,kFAAkF;YAChF,iBAAiB,WAAW,uBAAuB,MAAM,KAAK;YAC9D,+EAA+E;YAC/E,8EAA8E;YAC9E,yEAAyE;YACzE,6EAA6E;YAC7E,+EAA+E;YAC/E,iFAAiF;YACjF,wBAAwB,CAC3B,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;QACrC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AApBD,wDAoBC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,0BAA2B,SAAQ,KAAK;IAC1C,IAAI,GAAG,6BAAsC,CAAC;IACvD,iCAAiC;IACxB,IAAI,CAAS;IACtB,wCAAwC;IAC/B,OAAO,CAAoD;IAEpE,YAAY,IAAY,EAAE,OAA8C,EAAE,MAAc;QACtF,KAAK,CACH,mCAAmC,IAAI,qBAAqB,MAAM,GAAG;YACnE,iFAAiF;YACjF,6EAA6E;YAC7E,2EAA2E;YAC3E,CAAC,OAAO,KAAK,cAAc;gBACzB,CAAC,CAAC,4EAA4E;oBAC5E,0DAA0D;gBAC5D,CAAC,C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AI,CAAC,IAAI,CAAC,WAAW,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,SAAS,IAAI,CAC/E,CAAC;IACJ,CAAC;IAED,MAAM,MAAM,GAAG,EAAE;SACd,OAAO,CAAC,qBAAqB,UAAU,+BAA+B,CAAC;SACvE,GAAG,EAAqC,CAAC;IAC5C,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,EAAE,CAAC,OAAO,CAAC,eAAe,UAAU,4CAA4C,CAAC,CAAC,GAAG,CACnF,MAAM,CAAC,cAAc,CAAC,CACvB,CAAC;QACF,OAAO;IACT,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACnC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,cAAc,EAAE,CAAC;QACtD,MAAM,IAAI,0BAA0B,CAClC,IAAI,EACJ,cAAc,EACd,sCAAsC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,oBAAoB;YAC5E,iBAAiB,cAAc,GAAG,CACrC,CAAC;IACJ,CAAC;AACH,CAAC;AAED,kFAAkF;AAClF,SAAS,QAAQ,CAAC,GAAY;IAC5B,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC"}
@@ -50,6 +50,13 @@
50
50
  * purpose: hiding a cap inside auto-chunking decides a protocol question
51
51
  * for every consumer at once.
52
52
  * • `memorySessions()` — conversations in a Map, for tests and local dev.
53
+ * • `sqliteSessions({ file })` — the same port, in a file, so a restart is not
54
+ * an amnesia event. Conversations AND runs paused waiting on a person, in
55
+ * one table, on Node's built-in `node:sqlite` — nothing to install and no
56
+ * peer dependency. One machine, one file, one writer at a time is the
57
+ * stated ceiling; it is not a distributed store. Refuses BY NAME on a Node
58
+ * without `node:sqlite` rather than falling back to memory, because a store
59
+ * that silently forgot everything looks exactly like a new user.
53
60
  * • `standingAgent({ agent, sessions, host, durability? })` — the composer.
54
61
  * • `toEnvelope` / `readEnvelope` — pack a conversation, and refuse by name to
55
62
  * unpack a format this runtime does not know.
@@ -78,6 +85,8 @@ export type { NodeHost, NodeHostHandle, NodeHostOptions } from './nodeHost.js';
78
85
  export { httpHost, headerValue } from './httpHost.js';
79
86
  export type { ConversationHandshake, HandshakeFacts, HttpHost, HttpHostHandle, HttpHostOptions, HttpRequestFacts, HttpWire, } from './httpHost.js';
80
87
  export { memorySessions } from './memorySessions.js';
88
+ export { sqliteSessions, SqliteUnavailableError, UnreadableSessionFileError, } from './sqliteSessions.js';
89
+ export type { SqliteSessions, SqliteSessionsOptions } from './sqliteSessions.js';
81
90
  export { toEnvelope, toPausedEnvelope, readEnvelope, readPausedRun, checkEnvelope, } from './envelope.js';
82
91
  export { standingAgent } from './standingAgent.js';
83
92
  export { requireCapability, HostClosedError, ConcurrentRunError, PauseNotCarriedError, AwaitingDecisionError, NoPendingAskError, UnreadableEnvelopeError, ConversationClosedError, FrameTooLargeError, } from './errors.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hosting/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0EG;AAEH,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACnD,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAE/E,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACtD,YAAY,EACV,qBAAqB,EACrB,cAAc,EACd,QAAQ,EACR,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,QAAQ,GACT,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,aAAa,GACd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,oBAAoB,EACpB,qBAAqB,EACrB,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,YAAY,EACV,SAAS,EACT,kBAAkB,EAClB,sBAAsB,EACtB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,SAAS,EACT,WAAW,EACX,SAAS,EACT,iBAAiB,EACjB,UAAU,EACV,gBAAgB,EAChB,oBAAoB,EACpB,WAAW,EACX,UAAU,GACX,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hosting/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiFG;AAEH,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACnD,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAE/E,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACtD,YAAY,EACV,qBAAqB,EACrB,cAAc,EACd,QAAQ,EACR,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,QAAQ,GACT,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAI7B,YAAY,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,aAAa,GACd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,oBAAoB,EACpB,qBAAqB,EACrB,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,YAAY,EACV,SAAS,EACT,kBAAkB,EAClB,sBAAsB,EACtB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,SAAS,EACT,WAAW,EACX,SAAS,EACT,iBAAiB,EACjB,UAAU,EACV,gBAAgB,EAChB,oBAAoB,EACpB,WAAW,EACX,UAAU,GACX,MAAM,YAAY,CAAC"}
@@ -10,6 +10,9 @@
10
10
  * — which is also how the "a crashed process resumes the conversation" test is
11
11
  * written: keep the store, throw away everything else, and watch the
12
12
  * conversation come back through the envelope alone.
13
+ *
14
+ * The next step up ships beside this one: `sqliteSessions({ file })` is the same
15
+ * port in a file, with nothing to install.
13
16
  */
14
17
  import type { SessionLifecycle } from './types.js';
15
18
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"memorySessions.d.ts","sourceRoot":"","sources":["../../../src/hosting/memorySessions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAsB,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEvE;;;;;;GAMG;AACH,wBAAgB,cAAc,IAAI,gBAAgB,CASjD"}
1
+ {"version":3,"file":"memorySessions.d.ts","sourceRoot":"","sources":["../../../src/hosting/memorySessions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAsB,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEvE;;;;;;GAMG;AACH,wBAAgB,cAAc,IAAI,gBAAgB,CASjD"}
@@ -0,0 +1,212 @@
1
+ /**
2
+ * hosting/sqliteSessions — conversations in a file, so a restart is not an
3
+ * amnesia event.
4
+ *
5
+ * `memorySessions()` keeps conversations in a `Map` and says what that costs in
6
+ * its own docstring: restart the process and every conversation is gone. Until
7
+ * now the next step up was "bring a Redis", and the step between those two —
8
+ * *one machine, one file, nothing to install* — was a store every consumer had
9
+ * to write for themselves. This is that store.
10
+ *
11
+ * A paused run was in the same position from the other direction. `agent.run()`
12
+ * hands back a checkpoint that is documented as JSON you can keep anywhere, and
13
+ * "anywhere" was the whole of the offer: the library named a shape and left the
14
+ * keeping to you. Both halves land in the same table here, because
15
+ * {@link CheckpointEnvelope} was already a union of the two and a session store
16
+ * has no business caring which one it is holding.
17
+ *
18
+ * ── What this is, said plainly ──────────────────────────────────────────────
19
+ * **One process on one machine, writing one file.** That is the whole claim,
20
+ * and it is worth stating as a ceiling rather than leaving it to be discovered:
21
+ *
22
+ * • It survives a restart, a crash, a deploy — anything that ends the process
23
+ * and leaves the disk alone.
24
+ * • It is NOT a distributed store. Two machines do not share a session by
25
+ * both opening this file over a network filesystem, and nothing here tries
26
+ * to make that work.
27
+ * • WAL lets readers and one writer run at once, and **one writer at a time
28
+ * is the ceiling** — a second writer waits for the lock up to
29
+ * `busyTimeoutMs` and then fails loudly rather than queueing forever.
30
+ * Several processes on one box is fine at that scale; a fleet is not what
31
+ * this is.
32
+ *
33
+ * When you outgrow it you swap the one argument to `standingAgent`, which is
34
+ * the entire point of the port.
35
+ *
36
+ * ── Zero dependencies, and the version floor that buys ──────────────────────
37
+ * SQLite is *inside Node* — `node:sqlite`, no install, no native build, no
38
+ * peer dependency. The price is a version floor this package does not otherwise
39
+ * have: the module ships with Node 22.5 and newer. Rather than raise `engines`
40
+ * for one optional adapter and break every consumer on Node 20, the module is
41
+ * loaded when you actually construct a store, and its absence is refused by
42
+ * name with the version you are on and what to do about it — see
43
+ * {@link SqliteUnavailableError}. There is deliberately **no fallback to
44
+ * memory**: a store that silently forgot everything on restart is
45
+ * indistinguishable, from the outside, from a brand-new user.
46
+ *
47
+ * ── The two laws it inherits rather than re-implements ──────────────────────
48
+ * `checkEnvelope` is called on the way out AND on the way in, so an envelope
49
+ * whose `format` this runtime does not know is refused by name, and a stored
50
+ * session that is PRESENT but unreadable is refused by name too. Only a session
51
+ * that was never written hydrates as `undefined`. Validating on the way in as
52
+ * well is the cheap half of that promise: a row this store could not read back
53
+ * never gets written in the first place.
54
+ */
55
+ import type { SessionLifecycle } from './types.js';
56
+ /** One prepared statement, as this adapter calls it. */
57
+ export interface SqliteStatementLike {
58
+ run(...params: readonly unknown[]): unknown;
59
+ get(...params: readonly unknown[]): unknown;
60
+ all(...params: readonly unknown[]): unknown[];
61
+ }
62
+ /** One open database, as this adapter calls it. */
63
+ export interface SqliteDatabaseLike {
64
+ exec(sql: string): void;
65
+ prepare(sql: string): SqliteStatementLike;
66
+ close(): void;
67
+ }
68
+ /**
69
+ * The shape of `node:sqlite` this adapter needs — declared locally, the same
70
+ * way every other adapter here declares the slice of its backend it uses, so
71
+ * nothing takes a hard import on a module that does not exist on every
72
+ * supported Node.
73
+ */
74
+ export interface SqliteModuleLike {
75
+ new (path: string): SqliteDatabaseLike;
76
+ }
77
+ /** Options for {@link sqliteSessions}. */
78
+ export interface SqliteSessionsOptions {
79
+ /**
80
+ * The database file. Created if it does not exist, along with its parent
81
+ * directory — "no infrastructure" would be a thin promise if you still had to
82
+ * `mkdir` first.
83
+ *
84
+ * `':memory:'` is refused: it looks like a file, keeps nothing across a
85
+ * restart, and a store that quietly forgets is the exact failure this adapter
86
+ * exists to remove. Use `memorySessions()` when that is what you want — it
87
+ * says so in its name.
88
+ */
89
+ readonly file: string;
90
+ /**
91
+ * How long a write waits for another writer's lock before failing, in
92
+ * milliseconds. Default 5000.
93
+ *
94
+ * It fails rather than waits forever on purpose: a request hung on a lock
95
+ * looks exactly like a slow model, and the two need different fixes.
96
+ */
97
+ readonly busyTimeoutMs?: number;
98
+ /**
99
+ * @internal Test seam only — the `node:sqlite` module, injected. Lets the
100
+ * suite exercise the refusal path on a Node that HAS the module, and the
101
+ * failure paths without corrupting a real file. Not public API, not
102
+ * supported, and not a place to plug in another SQLite driver.
103
+ */
104
+ readonly _sqlite?: SqliteModuleLike;
105
+ }
106
+ /**
107
+ * A session store in a file.
108
+ *
109
+ * It is a {@link SessionLifecycle} plus the three things a real store owns
110
+ * beyond the port — closing, forgetting, and telling you what the file actually
111
+ * got — because the port deliberately asks for only two methods and leaves the
112
+ * rest to whoever implements it.
113
+ */
114
+ export interface SqliteSessions extends SessionLifecycle {
115
+ /**
116
+ * The journalling mode the file **actually has**, read back from SQLite
117
+ * rather than assumed from what was asked for.
118
+ *
119
+ * It is normally `'wal'`. It is something else when the file lives somewhere
120
+ * WAL cannot work — a network filesystem is the usual reason — and that is a
121
+ * fact worth being able to read: the store still works, with one writer *or*
122
+ * one reader at a time instead of both. A silent downgrade is the kind of
123
+ * thing that is only ever discovered under load.
124
+ */
125
+ readonly journalMode: string;
126
+ /** Forget one session. No-op if there is nothing stored for it. */
127
+ forget(sessionId: string): Promise<void>;
128
+ /**
129
+ * Close the file. Idempotent — a shutdown hook and an explicit close can
130
+ * coexist. Reading or writing afterwards refuses by name rather than
131
+ * reopening behind your back.
132
+ */
133
+ close(): void;
134
+ }
135
+ /**
136
+ * Raised when `node:sqlite` is not available in the running Node.
137
+ *
138
+ * Node 20 does not have the module at all; Node 22.5 through 22.12 have it
139
+ * behind `--experimental-sqlite`; Node 22.13+ and 23.4+ have it as-is (still
140
+ * marked experimental by Node, which is why it prints a warning on first use).
141
+ *
142
+ * The refusal names the version you are on and the three ways out, because
143
+ * "cannot find module 'node:sqlite'" out of a library's guts tells you what
144
+ * broke and nothing about what to do.
145
+ */
146
+ export declare class SqliteUnavailableError extends Error {
147
+ readonly code: "ERR_SQLITE_UNAVAILABLE";
148
+ /** The Node version this process is running. */
149
+ readonly nodeVersion: string;
150
+ constructor(nodeVersion: string, reason: string);
151
+ }
152
+ /**
153
+ * Raised when the file exists but this runtime cannot use it as a session
154
+ * store.
155
+ *
156
+ * The same law {@link UnreadableEnvelopeError} states for one stored value,
157
+ * one level up: **an unreadable store and an empty one are different facts, and
158
+ * only one of them is safe to answer with a fresh start.** A store that opened
159
+ * a corrupt file as an empty database would hand every returning user a blank
160
+ * slate and log nothing.
161
+ *
162
+ * `problem` is the fact to branch on — the three cases need different actions:
163
+ *
164
+ * - `'cannot-open'` — not a SQLite database, or not readable (permissions, a
165
+ * directory, a truncated file).
166
+ * - `'not-our-schema'` — a database whose `agent_sessions` table is somebody
167
+ * else's table of that name. Point the store at its own file.
168
+ * - `'newer-schema'` — written by a newer agentfootprint than this one. Same
169
+ * answer the envelope `format` field gives: refuse, never half-read.
170
+ */
171
+ export declare class UnreadableSessionFileError extends Error {
172
+ readonly code: "ERR_UNREADABLE_SESSION_FILE";
173
+ /** The file that was refused. */
174
+ readonly file: string;
175
+ /** Which of the three cases this is. */
176
+ readonly problem: 'cannot-open' | 'not-our-schema' | 'newer-schema';
177
+ constructor(file: string, problem: UnreadableSessionFileError['problem'], detail: string);
178
+ }
179
+ /**
180
+ * A session store in one SQLite file — the battery-included place to keep a
181
+ * conversation, or a run that stopped to ask a person something, so that a
182
+ * restart does not lose it.
183
+ *
184
+ * @throws SqliteUnavailableError when the running Node has no `node:sqlite`.
185
+ * @throws UnreadableSessionFileError when the file exists but cannot be used —
186
+ * never answered with an empty store.
187
+ *
188
+ * @example A standing agent whose conversations survive a restart
189
+ * import { standingAgent, nodeHost, sqliteSessions } from 'agentfootprint/hosting';
190
+ *
191
+ * const handle = await standingAgent({
192
+ * agent,
193
+ * sessions: sqliteSessions({ file: './sessions.db' }),
194
+ * host: nodeHost({ port: 8080 }),
195
+ * });
196
+ *
197
+ * @example Keeping a paused run yourself, without the composer
198
+ * const sessions = sqliteSessions({ file: './sessions.db' });
199
+ * const out = await agent.run({ message });
200
+ * if (isPaused(out)) {
201
+ * await sessions.persist(sessionId, toPausedEnvelope({
202
+ * checkpoint: out.checkpoint,
203
+ * conversation: agent.checkpoint()!,
204
+ * pending: { pauseData: out.pauseData },
205
+ * }));
206
+ * }
207
+ * // …a deploy later, in a new process:
208
+ * const paused = readPausedRun(await sessions.hydrate(sessionId));
209
+ * const answer = await agent.resume(paused.checkpoint, decision);
210
+ */
211
+ export declare function sqliteSessions(options: SqliteSessionsOptions): SqliteSessions;
212
+ //# sourceMappingURL=sqliteSessions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqliteSessions.d.ts","sourceRoot":"","sources":["../../../src/hosting/sqliteSessions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AAKH,OAAO,KAAK,EAAsB,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAIvE,wDAAwD;AACxD,MAAM,WAAW,mBAAmB;IAClC,GAAG,CAAC,GAAG,MAAM,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC;IAC5C,GAAG,CAAC,GAAG,MAAM,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC;IAC5C,GAAG,CAAC,GAAG,MAAM,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;CAC/C;AAED,mDAAmD;AACnD,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAAC;IAC1C,KAAK,IAAI,IAAI,CAAC;CACf;AAED;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,KAAK,IAAI,EAAE,MAAM,GAAG,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