oomi-ai 0.13.0 → 0.15.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.
@@ -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
+ }