oomi-ai 0.12.2 → 0.14.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,29 @@
1
+ // Runs the local gateway has started, by the gateway socket they started on. A closed socket
2
+ // can't deliver its runs' final events, so its runs stop counting as active; otherwise a lost
3
+ // final would keep the bridge from ever being idle, and a queued restart would expire.
4
+ export function createGatewayRuns() {
5
+ const bySocket = new Map();
6
+ return {
7
+ started(socketId, runId) {
8
+ if (!runId) return;
9
+ let runs = bySocket.get(socketId);
10
+ if (!runs) bySocket.set(socketId, (runs = new Set()));
11
+ runs.add(runId);
12
+ },
13
+ // A final can arrive on another socket after a reconnect.
14
+ finished(runId) {
15
+ for (const [socketId, runs] of bySocket) {
16
+ runs.delete(runId);
17
+ if (!runs.size) bySocket.delete(socketId);
18
+ }
19
+ },
20
+ closed(socketId) {
21
+ bySocket.delete(socketId);
22
+ },
23
+ get size() {
24
+ let count = 0;
25
+ for (const runs of bySocket.values()) count += runs.size;
26
+ return count;
27
+ },
28
+ };
29
+ }
package/lib/hermesAcp.js CHANGED
@@ -22,9 +22,6 @@ const IMAGE_TYPES = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'imag
22
22
  const SEED_MESSAGES = 12;
23
23
  const SEED_MESSAGE_CHARS = 800;
24
24
  const SEED_TOTAL_CHARS = 6000;
25
- const MAX_REPORTED_MODELS = 60;
26
- // Not models to talk with: images, video, speech, embeddings.
27
- const NOT_CHAT = /imagine|image|video|stt|tts|speech|audio|embed|whisper|moderation/i;
28
25
 
29
26
  // Only fixed messages cross the bridge; Hermes diagnostics may hold credentials or tool output.
30
27
  export class HermesAcpError extends Error {
@@ -79,29 +76,41 @@ class HermesAcpClient {
79
76
  this.turns = new Map();
80
77
  this.loaded = new Set();
81
78
  this.replayed = new Map();
82
- // The model each ACP session is on, and what Hermes offers (session/new and session/load
83
- // answers), for a call's faster model (Oomi's call.model, Voice::CallModel on the server).
79
+ // The model each ACP session is on and what Hermes can switch to (session/new and
80
+ // session/load answers), for `/model` in Talk and to put back a conversation an older bridge
81
+ // left on a call's model (restoreChatModel).
84
82
  this.sessionModels = new Map();
85
83
  this.availableModels = [];
86
- this.newSessionModel = '';
84
+ this.defaultModel = '';
87
85
  this.closed = false;
88
86
  this.ready = null;
89
87
  }
90
88
 
91
89
  noteModels(sessionId, models, { created = false } = {}) {
92
- if (!models || typeof models !== 'object') return;
93
- const current = typeof models.currentModelId === 'string' ? models.currentModelId : '';
90
+ const current = typeof models?.currentModelId === 'string' ? models.currentModelId : '';
94
91
  if (current) {
95
92
  this.sessionModels.set(sessionId, current);
96
- if (created) this.newSessionModel = current;
93
+ if (created) this.defaultModel = current;
97
94
  }
98
- if (Array.isArray(models.availableModels)) {
95
+ if (Array.isArray(models?.availableModels)) {
99
96
  this.availableModels = models.availableModels
100
97
  .filter((model) => typeof model?.modelId === 'string' && model.modelId)
101
98
  .map((model) => ({ id: model.modelId, name: typeof model.name === 'string' ? model.name : '' }));
102
99
  }
103
100
  }
104
101
 
102
+ /** The person's pick (`/model`): fixed errors only, since Hermes's own text may hold internals. */
103
+ async setModel(sessionId, modelId) {
104
+ if (this.turns.has(sessionId)) throw new HermesAcpError('hermes_busy', 'Hermes is answering in this conversation.');
105
+ try {
106
+ await this.request('session/set_model', { sessionId, modelId });
107
+ } catch (err) {
108
+ if (err.rpcCode === -32602) throw new HermesAcpError('hermes_unknown_model', 'Hermes can\'t use that model.');
109
+ throw err;
110
+ }
111
+ this.sessionModels.set(sessionId, modelId);
112
+ }
113
+
105
114
  /** Switches a session's model between turns (Hermes refuses mid-turn); false if it couldn't. */
106
115
  async switchModel(sessionId, modelId) {
107
116
  if (!modelId || this.turns.has(sessionId)) return false;
@@ -399,87 +408,55 @@ export async function runHermesAcpTurn(config, request, { signal, timeoutMs = 18
399
408
  const continuing = request.runtimeTransport === 'acp' ? request.runtimeSessionId : '';
400
409
  let { sessionId, created } = await client.openSession(continuing);
401
410
  const seed = () => continuityPreamble(request.history);
402
- let chatModel = await applyCallModel(client, sessionId, request);
411
+ let chatModel = await restoreChatModel(client, sessionId, request);
403
412
  let text;
404
413
  try {
405
- text = await client.prompt(sessionId, promptBlocks(request, created ? seed() : ''), { signal, timeoutMs, onText });
414
+ // A session `/model` opened for a conversation with history hasn't heard it yet.
415
+ text = await client.prompt(sessionId, promptBlocks(request, created || request.seedPending ? seed() : ''), { signal, timeoutMs, onText });
406
416
  } catch (err) {
407
417
  if (err.code !== 'hermes_session_unknown' || created) throw err;
408
418
  ({ sessionId } = await client.openSession(''));
409
- // A fresh session starts on the chat model.
410
- chatModel = await applyCallModel(client, sessionId, { ...request, chatModel: null });
419
+ // A fresh session starts on the persona's own model.
420
+ chatModel = null;
411
421
  text = await client.prompt(sessionId, promptBlocks(request, seed()), { signal, timeoutMs, onText });
412
422
  }
413
423
  return { text, sessionId, transport: 'acp', chatModel };
414
424
  }
415
425
 
416
426
  /**
417
- * A call turn asks for the persona's faster model (request.callModel); every other turn puts
418
- * the session back on the model it chats with. Returns the model to go back to, while the
419
- * session is on the call model (kept in the conversation's state, so a restart still restores
420
- * it), else null. A session whose model Hermes didn't say isn't switched: there'd be no way back.
427
+ * `/model` in Talk (docs/specs/chat-models-v1.md): the model a conversation's session is on, and
428
+ * what Hermes can switch it to (the providers its owner signed in to, as Telegram's picker lists).
429
+ * `create` makes a session when the conversation has none: true always, 'if-unknown' only when
430
+ * Hermes hasn't said its models yet. `session` is then `{ sessionId, created }` for the
431
+ * conversation to keep.
421
432
  */
422
- async function applyCallModel(client, sessionId, request) {
423
- const current = client.sessionModels.get(sessionId) || '';
424
- const remembered = typeof request.chatModel === 'string' && request.chatModel ? request.chatModel : null;
425
- const callModel = typeof request.callModel === 'string' && request.callModel ? request.callModel : '';
426
- if (callModel) {
427
- if (current === callModel) return remembered;
428
- if (!current) return remembered;
429
- const back = remembered || current;
430
- return (await client.switchModel(sessionId, callModel)) ? back : remembered;
431
- }
432
- if (remembered && current !== remembered) return (await client.switchModel(sessionId, remembered)) ? null : remembered;
433
- return null;
434
- }
435
-
436
- /**
437
- * What Hermes offers for a faster call model, for Oomi's persona page: the models of the provider
438
- * the persona chats with (chatModel, or the one new sessions start on), a recommendation (one
439
- * that doesn't reason first), and whether this runtime can switch. Null until Hermes has said.
440
- */
441
- export function hermesAcpModelReport(config, { chatModel = '' } = {}) {
442
- const client = clients.get(clientKey(config));
443
- if (!client || !client.availableModels.length) return null;
444
- const current = chatModel || client.newSessionModel || [...client.sessionModels.values()][0] || '';
445
- if (!current) return null;
446
- const provider = current.includes(':') ? current.slice(0, current.indexOf(':') + 1) : '';
447
- const available = client.availableModels
448
- .filter((model) => (!provider || model.id.startsWith(provider)) && !NOT_CHAT.test(model.id))
449
- .slice(0, MAX_REPORTED_MODELS)
450
- .map((model) => ({ id: model.id, name: modelDisplayName(model.id) }));
451
- if (!available.some((model) => model.id === current)) available.push({ id: current, name: modelDisplayName(current) });
452
- return { current, recommended: recommendedCallModel(available, current), switchable: true, available };
433
+ export async function hermesAcpModels(config, sessionId, { create = false } = {}) {
434
+ const client = hermesAcpClient(config);
435
+ await client.start();
436
+ const make = create === true || (create === 'if-unknown' && !client.availableModels.length);
437
+ const session = sessionId || make ? await client.openSession(sessionId || '', { create: make }) : null;
438
+ const current = (session && client.sessionModels.get(session.sessionId)) || client.defaultModel;
439
+ return { session, current, available: client.availableModels };
453
440
  }
454
441
 
455
- /** One that answers without reasoning first, else one built to be quick; never the chat model. */
456
- export function recommendedCallModel(available, current) {
457
- const others = available.filter((model) => model.id !== current);
458
- const plain = others.find((model) => /non[-_]?reasoning/i.test(model.id));
459
- if (plain) return plain.id;
460
- const quick = others.find((model) => /(^|[-_:/])(fast|flash|mini|lite|haiku|turbo|instant)([-_.]|$)/i.test(model.id) && !/code|coder|composer|build/i.test(model.id));
461
- return quick ? quick.id : null;
442
+ /** Switches a conversation's session (opened or made here) to `modelId`, for this conversation only. */
443
+ export async function setHermesAcpModel(config, sessionId, modelId) {
444
+ const client = hermesAcpClient(config);
445
+ await client.start();
446
+ const session = await client.openSession(sessionId || '');
447
+ await client.setModel(session.sessionId, modelId);
448
+ return { session, current: modelId, available: client.availableModels };
462
449
  }
463
450
 
464
- /** "xai-oauth:grok-4.20-0309-non-reasoning" → "Grok 4.20 (no reasoning)"; "claude-haiku-5-5" → "Claude Haiku 5.5". */
465
- export function modelDisplayName(id) {
466
- const text = String(id);
467
- const raw = (text.includes(':') ? text.slice(text.indexOf(':') + 1) : text).split(/[-_/\s]+/).filter(Boolean);
468
- let plain = false;
469
- const words = [];
470
- for (let index = 0; index < raw.length; index++) {
471
- const word = raw[index];
472
- if (/^non$/i.test(word) && /^reasoning$/i.test(raw[index + 1] || '')) { plain = true; index++; continue; }
473
- if (/^nonreasoning$/i.test(word)) { plain = true; continue; }
474
- if (/^\d{4}$/.test(word)) continue; // a release date
475
- // "5", "5" → "5.5"
476
- if (/^\d+$/.test(word) && words.length && /^\d+(\.\d+)?$/.test(words[words.length - 1]) && !words[words.length - 1].includes('.')) {
477
- words[words.length - 1] += `.${word}`;
478
- continue;
479
- }
480
- words.push(/^(gpt|glm|ai)$/i.test(word) ? word.toUpperCase() : /^[a-z]/.test(word) ? word[0].toUpperCase() + word.slice(1) : word);
481
- }
482
- const name = words.join(' ');
483
- return plain ? `${name} (no reasoning)` : name;
451
+ /**
452
+ * Calls answer on the model the persona is set up with; Oomi never switches it (Justin,
453
+ * 2026-10-22). oomi-ai 0.11.0-0.12.3 switched a session to a faster model on calls and kept the
454
+ * model to go back to in the conversation's state (request.chatModel): put such a session back.
455
+ * Returns the model still to go back to if Hermes couldn't switch now, else null.
456
+ */
457
+ async function restoreChatModel(client, sessionId, request) {
458
+ const remembered = typeof request.chatModel === 'string' && request.chatModel ? request.chatModel : null;
459
+ if (!remembered || client.sessionModels.get(sessionId) === remembered) return null;
460
+ return (await client.switchModel(sessionId, remembered)) ? null : remembered;
484
461
  }
485
462
 
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
3
4
  import WebSocket from 'ws';
4
5
 
5
6
  // Only fixed, sanitized messages cross the bridge. Gateway diagnostics may contain
@@ -28,11 +29,20 @@ function readLocalJson(file, missing) {
28
29
  function alive(pid) {
29
30
  try { process.kill(pid, 0); return true; } catch (err) { return err.code !== 'ESRCH'; }
30
31
  }
32
+ const PROFILE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
33
+ const LOCAL_HOSTS = new Set(['', '0.0.0.0', '127.0.0.1', '::', '::1', 'localhost']);
34
+ // A Hermes backend (`hermes serve` or the dashboard) listening on this computer only.
35
+ const localBackend = e => e?.isolated !== true && ['serve', 'dashboard'].includes(e?.purpose) && LOCAL_HOSTS.has(e.host || '') && Number.isInteger(e.port) && e.port > 0 && e.port <= 65535;
36
+ const backendBase = backend => `http://${backend.host === '::1' ? '[::1]' : '127.0.0.1'}:${backend.port}`;
37
+ /** The folder of the Hermes profile this connection talks to. */
38
+ export function hermesProfileHome(config) {
39
+ const profile = config.profile || 'default';
40
+ return profile === 'default' ? config.hermesHome : path.join(config.hermesHome, 'profiles', profile);
41
+ }
31
42
  function findOwner(config, sessionId) {
32
43
  const profile = config.profile || 'default';
33
- if (!config.hermesHome || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) throw hermesRefusal('SESSION_COORDINATION_UNAVAILABLE');
34
- const home = profile === 'default' ? config.hermesHome : path.join(config.hermesHome, 'profiles', profile);
35
- const raw = readLocalJson(path.join(home, 'runtime', 'active_sessions.json'), []);
44
+ if (!config.hermesHome || !PROFILE.test(profile)) throw hermesRefusal('SESSION_COORDINATION_UNAVAILABLE');
45
+ const raw = readLocalJson(path.join(hermesProfileHome(config), 'runtime', 'active_sessions.json'), []);
36
46
  const entries = Array.isArray(raw) ? raw : raw?.entries;
37
47
  if (!Array.isArray(entries) || entries.some(e => !e || typeof e.session_id !== 'string' || !Number.isInteger(e.pid) || e.pid <= 0)) throw hermesRefusal('SESSION_COORDINATION_UNAVAILABLE');
38
48
  const owners = entries.filter(e => e.session_id === sessionId && alive(e.pid));
@@ -40,11 +50,9 @@ function findOwner(config, sessionId) {
40
50
  if (owners.length !== 1) throw hermesRefusal('SESSION_COORDINATION_UNAVAILABLE');
41
51
  const owner = owners[0];
42
52
  const ledger = readLocalJson(path.join(config.hermesHome, 'spawn-ledger.json'), []);
43
- const hosts = new Set(['', '0.0.0.0', '127.0.0.1', '::', '::1', 'localhost']);
44
- const candidates = Array.isArray(ledger) ? ledger.filter(e => e?.pid === owner.pid && e.isolated !== true && ['serve', 'dashboard'].includes(e.purpose) && hosts.has(e.host || '') && Number.isInteger(e.port) && e.port > 0 && e.port <= 65535) : [];
53
+ const candidates = Array.isArray(ledger) ? ledger.filter(e => e?.pid === owner.pid && localBackend(e)) : [];
45
54
  if (!owner.metadata?.live_session_id || candidates.length !== 1) throw hermesRefusal('SESSION_NOT_OWNED');
46
- const backend = candidates[0];
47
- return { pid: owner.pid, liveId: owner.metadata.live_session_id, profile, base: `http://${backend.host === '::1' ? '[::1]' : '127.0.0.1'}:${backend.port}` };
55
+ return { pid: owner.pid, liveId: owner.metadata.live_session_id, profile, base: backendBase(candidates[0]) };
48
56
  }
49
57
 
50
58
  async function servedToken(base, signal) {
@@ -132,7 +140,11 @@ export async function runSharedHermesTurn(config, request, { signal, timeoutMs =
132
140
  if (payload?.persisted_turn?.user_row_id !== userRowId) return;
133
141
  if (payload.status !== 'complete' || !Number.isSafeInteger(payload.persisted_turn.final_assistant_row_id) || typeof payload.text !== 'string' || !payload.text.trim()) {
134
142
  completeReject(new HermesTurnError('hermes_turn_failed', 'Hermes did not finish this message. Check the same conversation in Hermes for its error or approval request before retrying.'));
135
- } else completeResolve({ text: payload.text.trim(), sessionId: request.runtimeSessionId });
143
+ } else {
144
+ // The rows Hermes stored for this turn, so they're never mistaken for messages typed there.
145
+ const rowIds = (Array.isArray(payload.persisted_turn.row_ids) ? payload.persisted_turn.row_ids : [userRowId, payload.persisted_turn.final_assistant_row_id]).filter(Number.isSafeInteger);
146
+ completeResolve({ text: payload.text.trim(), sessionId: request.runtimeSessionId, rowIds });
147
+ }
136
148
  };
137
149
  try {
138
150
  if (controller.signal.aborted) throw new Error();
@@ -183,3 +195,196 @@ export async function runSharedHermesTurn(config, request, { signal, timeoutMs =
183
195
  clearTimeout(timer); clearInterval(heartbeat); signal?.removeEventListener('abort', abort); controller.abort(); client?.close();
184
196
  }
185
197
  }
198
+
199
+ function servedBackend(config) {
200
+ const profile = config.profile || 'default';
201
+ if (!config.hermesHome || !PROFILE.test(profile)) return null;
202
+ let ledger;
203
+ try { ledger = readLocalJson(path.join(config.hermesHome, 'spawn-ledger.json'), []); } catch { return null; }
204
+ const backends = Array.isArray(ledger) ? ledger.filter(e => localBackend(e) && Number.isInteger(e.pid) && e.pid > 0 && alive(e.pid)) : [];
205
+ // Any backend reads any profile's conversations; prefer the one started for this profile.
206
+ const backend = backends.find(e => e.profile === profile) || backends.find(e => !e.profile) || backends[0];
207
+ return backend ? { base: backendBase(backend), profile } : null;
208
+ }
209
+
210
+ // GET from the Hermes backend serving this home, as JSON. Null when none is running; the status
211
+ // alone for a 404. `tokens` remembers each backend's served token between reads.
212
+ async function backendGet(config, query, { tokens, signal }) {
213
+ const backend = servedBackend(config);
214
+ if (!backend) return null;
215
+ const separator = query.includes('?') ? '&' : '?';
216
+ const url = `${backend.base}${query}${separator}profile=${encodeURIComponent(backend.profile)}`;
217
+ // A backend restarted since the last read serves a new token: fetch it once more.
218
+ for (let attempt = 0; attempt < 2; attempt++) {
219
+ let token = tokens.get(backend.base);
220
+ if (!token) { token = await servedToken(backend.base, signal); tokens.set(backend.base, token); }
221
+ const response = await fetch(url, { headers: { 'X-Hermes-Session-Token': token }, redirect: 'error', signal });
222
+ if (response.status === 401 || response.status === 403) { tokens.delete(backend.base); await response.body?.cancel(); continue; }
223
+ if (response.status === 404) { await response.body?.cancel(); return { status: 404 }; }
224
+ if (!response.ok) { await response.body?.cancel(); throw new Error('Hermes could not answer this read.'); }
225
+ let body = '';
226
+ for await (const chunk of response.body) {
227
+ body += Buffer.from(chunk).toString('utf8');
228
+ if (body.length > 8 * 1024 * 1024) throw new Error('Hermes returned too much.');
229
+ }
230
+ return { status: response.status, body: JSON.parse(body) };
231
+ }
232
+ throw new Error('Hermes did not accept its served token.');
233
+ }
234
+
235
+ const seconds = value => { const n = Number(value); return Number.isFinite(n) ? (n > 1e12 ? n / 1000 : n) : NaN; };
236
+
237
+ /**
238
+ * Since when (Hermes seconds) no Hermes backend can have started: null while one is running; else
239
+ * the last write to the backend ledger, which every backend makes when it starts (0 with no
240
+ * ledger). Other Hermes processes write it too, so this only ever errs towards "maybe one ran".
241
+ */
242
+ export function hermesBackendQuietSince(config) {
243
+ if (servedBackend(config)) return null;
244
+ try { return fs.statSync(path.join(config.hermesHome, 'spawn-ledger.json')).mtimeMs / 1000; } catch (err) { return err.code === 'ENOENT' ? 0 : null; }
245
+ }
246
+
247
+ /** The backend ledger as it is now (time, size and contents): any backend starting changes it. */
248
+ export function hermesLedgerSignature(config) {
249
+ const file = path.join(config.hermesHome, 'spawn-ledger.json');
250
+ try {
251
+ const stat = fs.statSync(file);
252
+ return `${stat.mtimeMs}:${stat.size}:${createHash('sha256').update(fs.readFileSync(file)).digest('hex')}`;
253
+ } catch (err) { return err.code === 'ENOENT' ? 'none' : `unreadable:${Date.now()}`; }
254
+ }
255
+
256
+ /**
257
+ * When each conversation last changed (Hermes seconds), from the backend's session list, most
258
+ * recent first. It pages until it reaches conversations unchanged since `since`, at most
259
+ * `maxPages` pages; `complete` is false when it stopped short, and every conversation not listed
260
+ * then changed no later than `oldest`. Null when no Hermes backend runs.
261
+ */
262
+ export async function readHermesActivity(config, { since = 0, tokens = new Map(), pageSize = 100, maxPages = 50, timeoutMs = 10000 } = {}) {
263
+ const signal = AbortSignal.timeout(timeoutMs);
264
+ const activity = new Map();
265
+ let oldest = Infinity;
266
+ for (let page = 0; page < maxPages; page++) {
267
+ const read = await backendGet(config, `/api/sessions?limit=${pageSize}&offset=${page * pageSize}&order=recent&archived=include`, { tokens, signal });
268
+ if (!read) return null;
269
+ const sessions = Array.isArray(read.body?.sessions) ? read.body.sessions : [];
270
+ for (const session of sessions) {
271
+ const at = seconds(session?.last_active ?? session?.started_at);
272
+ if (typeof session?.id === 'string' && Number.isFinite(at)) { activity.set(session.id, at); oldest = Math.min(oldest, at); }
273
+ }
274
+ if (sessions.length < pageSize || oldest <= since) return { activity, complete: true, oldest };
275
+ }
276
+ return { activity, complete: false, oldest };
277
+ }
278
+
279
+ // What a read keeps of a row: tool output and the like can be large and is never copied.
280
+ const keptRow = row => (row?.role === 'user' || row?.role === 'assistant' ? row : { id: row?.id, role: row?.role, timestamp: row?.timestamp });
281
+ /** How a transcript row is told apart from another at the same time: Hermes's row id. */
282
+ export const rowKey = row => (Number.isSafeInteger(row?.id) ? row.id : JSON.stringify([row?.role, row?.timestamp, row?.content]));
283
+ const messagesQuery = (sessionId, order, offset, limit) => `/api/sessions/${encodeURIComponent(sessionId)}/messages?limit=${limit}&offset=${offset}&order=${order}&include_compacted=true&inline_images=false`;
284
+
285
+ /**
286
+ * One conversation as Hermes shows it on this computer (the transcript Hermes desktop and oomi's
287
+ * Talk read, `GET /api/sessions/{id}/messages`, archived history included): rows from `after`
288
+ * (Hermes seconds) on, oldest first, leaving out the rows at exactly `after` listed in `skip`
289
+ * (their `rowKey`s: already read). Rows can share a time, so a checkpoint is a time and the rows
290
+ * already read at it.
291
+ *
292
+ * It reads newest first, up to `maxPages` pages; that reaches `after` in the usual case and the
293
+ * read is `covered`. Further behind, it finds the first row at or after `after` and reads forward
294
+ * from there, at most `chunkPages` pages of new rows: `covered` is then false unless that reached
295
+ * the newest row, and `through` is the newest time read, so the caller can apply this much and
296
+ * come back for the rest. Null when no Hermes backend is running for this home.
297
+ */
298
+ export async function readHermesTranscript(config, sessionId, { after = 0, skip = [], tokens = new Map(), pageSize = 100, maxPages = 5, chunkPages = 20, timeoutMs = 30000 } = {}) {
299
+ if (typeof sessionId !== 'string' || !sessionId) return null;
300
+ const signal = AbortSignal.timeout(timeoutMs);
301
+ const get = (order, offset, limit) => backendGet(config, messagesQuery(sessionId, order, offset, limit), { tokens, signal });
302
+ const rows = [];
303
+ const seen = new Set();
304
+ const read = new Set(skip);
305
+ const take = batch => batch.filter(row => {
306
+ const key = rowKey(row);
307
+ if (seen.has(key)) return false; // Rows written meanwhile shift newest-first pages.
308
+ seen.add(key);
309
+ const at = seconds(row?.timestamp);
310
+ return at > after || (at === after && !read.has(key));
311
+ }).map(keptRow);
312
+ for (let page = 0; page < maxPages; page++) {
313
+ const read = await get('latest', page * pageSize, pageSize);
314
+ if (!read) return null;
315
+ if (read.status === 404) return { rows: [], covered: true };
316
+ const batch = Array.isArray(read.body?.messages) ? read.body.messages : [];
317
+ rows.unshift(...take(batch));
318
+ // Rows at exactly `after` can run on into the next page: only an earlier one shows the end.
319
+ if (batch.length < pageSize || batch.some(row => seconds(row?.timestamp) < after)) return { rows, covered: true };
320
+ }
321
+
322
+ // Far behind: the first row at or after `after`, oldest first (exponential, then binary search).
323
+ const at = async offset => {
324
+ const read = await get('oldest', offset, 1);
325
+ if (!read) throw new Error('Hermes stopped while reading.');
326
+ const row = Array.isArray(read.body?.messages) ? read.body.messages[0] : undefined;
327
+ return row ? seconds(row.timestamp) : Infinity; // Past the end counts as after.
328
+ };
329
+ let low = -1, high = 1;
330
+ while (await at(high) < after) { low = high; high *= 2; }
331
+ while (high - low > 1) {
332
+ const middle = Math.floor((low + high) / 2);
333
+ if (await at(middle) < after) low = middle; else high = middle;
334
+ }
335
+ // Times aren't strictly ordered across compaction; start a few rows early and filter.
336
+ const start = Math.max(0, high - 10);
337
+ seen.clear();
338
+ const forward = [];
339
+ // Pages with nothing new don't count, so every chunk gets further.
340
+ for (let page = 0; page < chunkPages || !forward.length; page++) {
341
+ const read = await get('oldest', start + page * pageSize, pageSize);
342
+ if (!read) return null;
343
+ const batch = Array.isArray(read.body?.messages) ? read.body.messages : [];
344
+ forward.push(...take(batch));
345
+ if (batch.length < pageSize) return { rows: forward, covered: true };
346
+ }
347
+ const through = Math.max(after, ...forward.map(row => seconds(row.timestamp)).filter(Number.isFinite));
348
+ return { rows: forward, covered: false, through };
349
+ }
350
+
351
+ function contentText(value) {
352
+ if (typeof value === 'string') {
353
+ if (!value.startsWith('\u0000json:')) return value;
354
+ try { return contentText(JSON.parse(value.slice(6))); } catch { return ''; }
355
+ }
356
+ if (!Array.isArray(value)) return '';
357
+ return value.map(part => typeof part === 'string' ? part : part?.type === 'text' && typeof part.text === 'string' ? part.text : '').join('');
358
+ }
359
+
360
+ // What the person typed, without the files and pictures Talk attaches to it (Talk's StoredUserText).
361
+ function typedText(text) {
362
+ const lines = text.split('\n');
363
+ let kept = lines.filter(line => !line.startsWith('@image:'));
364
+ if (kept.length !== lines.length) kept = kept.filter(line => line.trimEnd() !== '[screenshot]');
365
+ let first = 0;
366
+ while (first < kept.length && (kept[first].startsWith('@file:') || kept[first].startsWith('@folder:'))) first++;
367
+ return first === 0 && kept.length === lines.length ? text : kept.slice(first).join('\n').trim();
368
+ }
369
+
370
+ /**
371
+ * The person's messages and the persona's replies in a Hermes transcript, as Talk shows them:
372
+ * no tool rows, notices, hidden or failed rows, compaction summaries, gateway scaffolding or
373
+ * oomi's own control messages. Timestamps are Hermes's (seconds); `id` is Hermes's row id.
374
+ */
375
+ export function hermesTranscriptTurns(rows) {
376
+ const turns = [];
377
+ for (const row of Array.isArray(rows) ? rows : []) {
378
+ if (!row || typeof row !== 'object' || (row.role !== 'user' && row.role !== 'assistant')) continue;
379
+ if (row.display_kind || row._compressed_summary) continue;
380
+ const timestamp = Number(row.timestamp);
381
+ if (!Number.isFinite(timestamp) || timestamp <= 0) continue;
382
+ let text = contentText('display_content' in row ? row.display_content : row.content).trim();
383
+ if (row.role === 'user') {
384
+ text = typedText(text);
385
+ if (text.startsWith('[System:') || text.startsWith('⟦oomi:') || /\[oomi:(primer|cue)/.test(text)) continue;
386
+ }
387
+ if (text) turns.push({ role: row.role, text, timestamp, ...(Number.isSafeInteger(row.id) ? { id: row.id } : {}) });
388
+ }
389
+ return turns;
390
+ }