oomi-ai 0.13.0 → 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.
package/README.md CHANGED
@@ -113,6 +113,8 @@ Use the user's app URL when provided. Hermes supports `--profile <profile>` and
113
113
 
114
114
  Shared desktop conversations require Hermes's loopback WebSocket gateway, active-session discovery, and durable prompt/reply row IDs. Busy conversations ask you to retry after the current task. If a simultaneous desktop send queues your message without a reply receipt, or the connection drops after sending, check the same Hermes chat before resending. Oomi cannot safely repeat an uncertain action. Human approvals stay in the existing Hermes desktop UI. Shared photo submission is not yet supported; use Hermes desktop for that photo. Older or terminal-only owners without a shared gateway receive an actionable error, never a competing process. The shared owner keeps its existing environment, so use the explicit Oomi `--connection NAME` for account commands.
115
115
 
116
+ From 0.14.0, messages the person types to the persona on the computer, in a conversation Oomi shares (Hermes desktop, or oomi's Talk showing the phone's conversation), join that Oomi conversation with the persona's reply, and the person's open Oomi chats (web, phone) reload within about a second. The bridge watches Hermes's `state.db` and reads the conversation from the running Hermes backend's transcript (`/api/sessions/{id}/messages`, the one Hermes desktop shows), only between its own turns. It copies what the person and the persona said, never tool output, and starts counting from its first run with this release; earlier computer messages aren't copied. Its own phone and web turns are recognised by Hermes's row ids or by their words, never by the time alone, and a phone or web message first picks up what was just typed on the computer, so the order holds. It reads only conversations Hermes changed, back to its last look; far behind, it reads forward from the last look a chunk at a time, so nothing is skipped. While no Hermes backend runs, nothing on the computer but the bridge (and Hermes's CLI by hand) can write to its conversations, so its own turns are settled without a read; rows written while a backend ran are picked up when one runs again, retried every 30 seconds and as soon as one starts. A phone or web turn waits at most a quarter second for what was just typed on the computer. A conversation record keeps its newest 1,000 messages and 200 finished receipts; a receipt for an action that never finished is always kept.
117
+
116
118
  The command verifies a real local reply, reuses saved credentials or pairs once, starts the bridge, waits for Oomi's subscription, then creates a single-use Auth Link. Failed verification means setup is incomplete: repair the selected runtime, never substitute a different one.
117
119
 
118
120
  The installer is an alternative to npm plus connect, and requires an explicit runtime:
package/bin/oomi-ai.js CHANGED
@@ -2820,6 +2820,26 @@ async function startOpenclawBridge(flags) {
2820
2820
  );
2821
2821
  };
2822
2822
 
2823
+ // Messages typed to the persona on this computer joined a conversation: Oomi tells the phone
2824
+ // and the web to reload it. Held until DeviceChannel confirms this connection's subscription.
2825
+ let conversationChangesReady = false;
2826
+ const pendingConversationChanges = new Map();
2827
+ const flushConversationChanges = () => {
2828
+ if (!conversationChangesReady || currentBrokerSocket?.readyState !== WebSocket.OPEN) return;
2829
+ for (const [sessionKey, reason] of pendingConversationChanges) {
2830
+ sendBrokerPayload(currentBrokerSocket, { action: 'conversation_changed', type: 'conversation.changed', sessionKey, reason });
2831
+ }
2832
+ pendingConversationChanges.clear();
2833
+ };
2834
+ if (localRuntime) {
2835
+ localRuntime.onConversationChanged = ({ sessionKey, reason }) => {
2836
+ if (!actionCableMode) return;
2837
+ pendingConversationChanges.set(sessionKey, pendingConversationChanges.get(sessionKey) === 'reply' ? 'reply' : reason);
2838
+ flushConversationChanges();
2839
+ };
2840
+ }
2841
+ const stopComputerTurns = localRuntime ? localRuntime.watchComputerTurns() : () => {};
2842
+
2823
2843
  const sendGatewayAck = (brokerSocket, {
2824
2844
  sessionId,
2825
2845
  requestId = '',
@@ -3555,6 +3575,7 @@ async function startOpenclawBridge(flags) {
3555
3575
 
3556
3576
  brokerSocket.on('open', () => {
3557
3577
  bridgeDebugLog('[bridge] Connected to managed broker.');
3578
+ conversationChangesReady = false;
3558
3579
  reconnectState.attempt = 0;
3559
3580
  reconnectState.lastFailure = null;
3560
3581
  if (actionCableMode) {
@@ -3594,6 +3615,8 @@ async function startOpenclawBridge(flags) {
3594
3615
 
3595
3616
  if (payload.type === 'device.subscribed') {
3596
3617
  deviceChannelSubscribed = true;
3618
+ conversationChangesReady = true;
3619
+ flushConversationChanges();
3597
3620
  updateBridgeStatus({
3598
3621
  status: 'connected',
3599
3622
  deviceId,
@@ -3880,6 +3903,7 @@ async function startOpenclawBridge(flags) {
3880
3903
  }));
3881
3904
 
3882
3905
  brokerSocket.on('close', runBridgeCallbackSafely((code, reason) => {
3906
+ conversationChangesReady = false;
3883
3907
  if (actionCableHeartbeat) {
3884
3908
  clearInterval(actionCableHeartbeat);
3885
3909
  actionCableHeartbeat = null;
@@ -3931,6 +3955,7 @@ async function startOpenclawBridge(flags) {
3931
3955
  reconnectState.stopped = true;
3932
3956
  clearInterval(maintenanceTimer);
3933
3957
  stopChannelWorker();
3958
+ stopComputerTurns();
3934
3959
  stopIdentityWorker();
3935
3960
  stopRoutineWorker();
3936
3961
  agentChannelWorker.stop();
@@ -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
+ }
package/lib/localAgent.js CHANGED
@@ -4,7 +4,7 @@ import os from 'node:os';
4
4
  import { spawn } from 'node:child_process';
5
5
  import { EventEmitter } from 'node:events';
6
6
  import { createHash, randomUUID } from 'node:crypto';
7
- import { runSharedHermesTurn, hermesRefusal } from './hermesGateway.js';
7
+ import { runSharedHermesTurn, hermesRefusal, readHermesTranscript, readHermesActivity, hermesTranscriptTurns, hermesProfileHome, hermesBackendQuietSince, hermesLedgerSignature, rowKey } from './hermesGateway.js';
8
8
  import { runHermesAcpTurn, hermesAcpAvailable, resetHermesAcp, warmHermesAcp, hermesAcpModels, setHermesAcpModel, continuityPreamble } from './hermesAcp.js';
9
9
  import { CHAT_MODELS_CAPABILITY, ChatModelsError, hermesEntries, matchModel, modelChoice, modelsAnswer } from './chatModels.js';
10
10
  import { grokbotConfig, runGrokbotTurn, completedGrokbotTurn } from './grokbotRuntime.js';
@@ -74,6 +74,104 @@ export function readJson(file, fallback = {}) {
74
74
  }
75
75
  }
76
76
 
77
+ // A conversation record keeps its newest messages (chat.history shows at most 500), its newest
78
+ // finished receipts, and the bridge's own turns not yet matched against Hermes's transcript.
79
+ const KEPT_MESSAGES = 1000;
80
+ const KEPT_RECEIPTS = 200;
81
+ const KEPT_OWN_TURNS = 2000;
82
+ // A look reads at most this many conversations; a phone turn waits at most this long for its catch-up.
83
+ const MAX_READS_PER_LOOK = 25;
84
+ const CATCH_UP_WAIT_MS = 250;
85
+ function keepRecentMessages(state) {
86
+ if (state.messages.length > KEPT_MESSAGES) state.messages = state.messages.slice(-KEPT_MESSAGES);
87
+ }
88
+ /**
89
+ * Keeps a record's newest 200 finished receipts (replies kept for retries of the same message, or
90
+ * a message known not to have started). A receipt for an action that started and never finished
91
+ * is never dropped: retrying that message must keep refusing, whatever came after.
92
+ */
93
+ export function keepRecentReceipts(state) {
94
+ const finished = Object.keys(state.receipts || {}).filter((key) => state.receipts[key]?.result || state.receipts[key]?.status === 'not_started');
95
+ for (const key of finished.slice(0, Math.max(0, finished.length - KEPT_RECEIPTS))) delete state.receipts[key];
96
+ }
97
+
98
+ const fingerprint = (text) => createHash('sha256').update(text).digest('hex').slice(0, 24);
99
+
100
+ /**
101
+ * How a turn of the bridge's own is recognised in Hermes's transcript, without keeping its words:
102
+ * its window, a fingerprint of what it sent (`sent`, and its length `sentLength`: Hermes may put a
103
+ * continuity note in front), of its reply (`reply`), and Hermes's row ids when the shared gateway
104
+ * gave them. A `quiet` entry is a stretch when no Hermes backend ran: every row in it is its own.
105
+ */
106
+ export function ownTurnEntry({ start, end, text, reply, rowIds }) {
107
+ const sent = typeof text === 'string' ? text.trim() : '';
108
+ const answer = typeof reply === 'string' ? reply.trim() : '';
109
+ return { start, end, ...(sent ? { sent: fingerprint(sent), sentLength: sent.length } : {}), ...(answer ? { reply: fingerprint(answer) } : {}), ...(Array.isArray(rowIds) && rowIds.length ? { rowIds } : {}) };
110
+ }
111
+
112
+ /** The rows among `turns` that are the bridge's own, by the entries in `state.ownTurns`. */
113
+ function ownRowsOf(turns, ownTurns) {
114
+ const own = new Set();
115
+ for (const turn of ownTurns) {
116
+ const inWindow = turns.filter((row) => row.timestamp >= turn.start && row.timestamp <= turn.end && !own.has(row));
117
+ if (turn.quiet) { for (const row of inWindow) own.add(row); continue; }
118
+ const ids = new Set(Array.isArray(turn.rowIds) ? turn.rowIds : []);
119
+ const byId = inWindow.filter((row) => ids.has(row.id));
120
+ if (byId.length) { for (const row of byId) own.add(row); continue; }
121
+ // The words it sent through its reply.
122
+ const sentLength = Number(turn.sentLength) || 0;
123
+ const first = turn.sent ? inWindow.findIndex((row) => row.role === 'user' && row.text.length >= sentLength && fingerprint(row.text.slice(row.text.length - sentLength)) === turn.sent) : -1;
124
+ if (first < 0) { for (const row of inWindow) own.add(row); continue; } // Can't tell: never show its own turn twice.
125
+ let last = inWindow.length - 1;
126
+ if (turn.reply) {
127
+ const at = inWindow.findLastIndex((row) => row.role === 'assistant' && fingerprint(row.text) === turn.reply);
128
+ if (at >= first) last = at;
129
+ }
130
+ for (const row of inWindow.slice(first, last + 1)) own.add(row);
131
+ }
132
+ return own;
133
+ }
134
+
135
+ /**
136
+ * Adds what was typed on the computer, and the persona's replies there, to a conversation record
137
+ * from a read of its Hermes transcript (`rows` from the record's checkpoint on, read at `readAt`).
138
+ * A read that stopped short (`covered: false`) has every row up to `through`. Rows of the
139
+ * bridge's own turns are left out. The checkpoint moves to the newest time read, with the rows
140
+ * read at that time (`computerTurnsTie`): rows can share a time, and the next read starts there.
141
+ * Returns the messages added and whether the record changed.
142
+ */
143
+ export function applyComputerRows(state, { rows, readAt, covered = true, through: readThrough }) {
144
+ const through = Number(state.computerTurnsThrough) || 0;
145
+ const tie = new Set(Array.isArray(state.computerTurnsTie) ? state.computerTurnsTie : []);
146
+ const ownTurns = Array.isArray(state.ownTurns) ? state.ownTurns : [];
147
+ const later = (Array.isArray(rows) ? rows : []).filter((row) => {
148
+ const at = Number(row?.timestamp);
149
+ return at > through || (at === through && !tie.has(rowKey(row)));
150
+ });
151
+ const turns = hermesTranscriptTurns(later);
152
+ const own = ownRowsOf(turns, ownTurns);
153
+ const added = turns.filter((row) => !own.has(row));
154
+ for (const row of added) {
155
+ const timestamp = Math.round(row.timestamp * 1000);
156
+ state.messages.push(row.role === 'user'
157
+ ? { role: 'user', content: row.text, timestamp, origin: 'computer' }
158
+ : { role: 'assistant', content: [{ type: 'text', text: row.text }], timestamp, origin: 'computer' });
159
+ }
160
+ keepRecentMessages(state);
161
+ const newest = Math.max(through, ...later.map((row) => Number(row.timestamp)).filter(Number.isFinite));
162
+ const atNewest = later.filter((row) => Number(row.timestamp) === newest).map(rowKey);
163
+ const nextTie = newest === through ? [...tie, ...atNewest] : atNewest;
164
+ state.computerTurnsThrough = newest;
165
+ if (nextTie.length) state.computerTurnsTie = nextTie; else delete state.computerTurnsTie;
166
+ // Read from a running backend: one was up at this checkpoint.
167
+ if (newest !== through) delete state.computerTurnsQuiet;
168
+ // A turn that ended before everything read has all its rows in it.
169
+ const seenThrough = covered ? readAt : Number(readThrough) || newest;
170
+ const pending = ownTurns.filter((turn) => !(turn.end < seenThrough));
171
+ if (pending.length) state.ownTurns = pending; else delete state.ownTurns;
172
+ return { added, changed: added.length > 0 || newest !== through || atNewest.length > 0 || pending.length !== ownTurns.length };
173
+ }
174
+
77
175
  export function localAgentConfig(flags) {
78
176
  const runtime = String(flags.runtime || '');
79
177
  if (runtime === 'grokbot') return grokbotConfig(flags, flags.connectionDirectory);
@@ -232,9 +330,18 @@ export class LocalAgentRuntime {
232
330
  this.queue = Promise.resolve();
233
331
  this.active = new Map();
234
332
  this.deliveries = 0;
333
+ // Told { sessionKey, reason } when messages typed on this computer join a conversation.
334
+ this.onConversationChanged = null;
335
+ // Older records don't say which conversation they are; chat.history tells us.
336
+ this.sessionKeys = new Map();
337
+ this.hermesTokens = new Map();
235
338
  }
236
339
  file(sessionKey) { return path.join(this.directory, 'conversations', createHash('sha256').update(sessionKey).digest('hex') + '.json'); }
237
- history(sessionKey) { return readJson(this.file(sessionKey), { messages: [], receipts: {} }); }
340
+ history(sessionKey) {
341
+ const file = this.file(sessionKey);
342
+ if (sessionKey) this.sessionKeys.set(path.basename(file), sessionKey);
343
+ return readJson(file, { messages: [], receipts: {} });
344
+ }
238
345
  async turn({ sessionKey, message, idempotencyKey, attachments = [], retryInterrupted = false, onText, onStarted, oomi, sandbox = false }) {
239
346
  const images = readImageAttachments(attachments);
240
347
  const text = typeof message === 'string' ? message : '';
@@ -251,8 +358,10 @@ export class LocalAgentRuntime {
251
358
  }
252
359
  const receiptKey = createHash('sha256').update(idempotencyKey).digest('hex');
253
360
  const controller = new AbortController();
361
+ // What was typed on the computer since the last look goes in before this message.
362
+ const catchUp = this.readCatchUp(sessionKey);
254
363
  const promise = this.queue.then(async () => {
255
- const state = this.history(sessionKey);
364
+ let state = this.history(sessionKey);
256
365
  const previous = state.receipts[receiptKey];
257
366
  if (previous?.message !== undefined && previous.message !== message) throw new Error('Idempotency key was reused for a different message.');
258
367
  if (previous && (previous.practiceDigest || null) !== practiceDigest) throw new Error('Idempotency key was reused for different practice context.');
@@ -262,8 +371,16 @@ export class LocalAgentRuntime {
262
371
  const resumedReply = previous && this.config.runtime === 'grokbot' ? completedGrokbotTurn(this.config, { sessionKey, message: prompt, idempotencyKey, runtimeSessionId: state.runtimeSessionId || this.config.resume }) : null;
263
372
  if (previous && previous.status !== 'not_started' && !retryInterrupted && !resumedReply) throw new Error('The previous turn was interrupted. Check the agent before sending a new message.');
264
373
  if (controller.signal.aborted) throw new Error('Agent turn cancelled.');
374
+ // What was typed on the computer since the last look comes before this message.
375
+ if (!previous) {
376
+ const caught = await Promise.race([catchUp, new Promise((resolve) => setTimeout(resolve, CATCH_UP_WAIT_MS, null))]);
377
+ if (caught && this.applyComputerReads([caught.name], caught.reads, caught.readStart).added) state = this.history(sessionKey);
378
+ }
265
379
  state.receipts[receiptKey] = { message, practiceDigest, status: 'running' };
266
380
  writePrivateJson(this.file(sessionKey), state);
381
+ // When this turn began in Hermes, so its rows are never taken for messages typed on the computer.
382
+ const turnStart = Date.now() / 1000;
383
+ const quietAtStart = this.config.runtime === 'hermes' && !!this.config.hermesHome && hermesBackendQuietSince(this.config) !== null;
267
384
  let scratch;
268
385
  let started = previous?.status === 'started';
269
386
  const confirmStarted = () => {
@@ -283,6 +400,7 @@ export class LocalAgentRuntime {
283
400
  : { sessionKey, message: prompt, idempotencyKey, history: state.messages, runtimeSessionId: state.runtimeSessionId || this.config.resume, runtimeTransport: state.runtimeTransport, imagePaths: scratch?.paths || [], chatModel: state.runtimeChatModel || null, seedPending: state.runtimeSeedPending === true };
284
401
  const result = resumedReply || await runLocalAgent(this.config, request, { signal: controller.signal, onText: text => { confirmStarted(); onText?.(text); }, onStarted: confirmStarted });
285
402
  confirmStarted();
403
+ state.sessionKey = sessionKey;
286
404
  if (sandbox) {
287
405
  if (result.sessionId) state.sandboxSessionId = result.sessionId;
288
406
  } else {
@@ -297,15 +415,19 @@ export class LocalAgentRuntime {
297
415
  else delete state.runtimeChatModel;
298
416
  }
299
417
  state.messages.push({ role: 'user', content: userContent(text, images), timestamp: Date.now() }, { role: 'assistant', content: [{ type: 'text', text: result.text }], timestamp: Date.now() });
418
+ if (!sandbox) this.rememberOwnTurn(state, { start: turnStart, quietAtStart, text: prompt, reply: result.text, rowIds: result.rowIds });
419
+ keepRecentMessages(state);
300
420
  state.receipts[receiptKey] = { message, practiceDigest, result };
421
+ keepRecentReceipts(state);
301
422
  writePrivateJson(this.file(sessionKey), state);
302
423
  this.onHealth({ runtimeReady: true, lastReplyAt: new Date().toISOString(), lastErrorMessage: '' });
303
424
  return { ...result, started: true };
304
425
  } catch (err) {
305
- if (err.notStarted === true && !started) {
306
- state.receipts[receiptKey] = { message, practiceDigest, status: 'not_started' };
307
- writePrivateJson(this.file(sessionKey), state);
308
- }
426
+ const notStarted = err.notStarted === true && !started;
427
+ if (notStarted) state.receipts[receiptKey] = { message, practiceDigest, status: 'not_started' };
428
+ keepRecentReceipts(state);
429
+ // Hermes may have kept the message that failed; it was sent from here, not typed on the computer.
430
+ if (notStarted || (!sandbox && this.rememberOwnTurn(state, { start: turnStart, quietAtStart, text: prompt }))) writePrivateJson(this.file(sessionKey), state);
309
431
  this.onHealth({ runtimeReady: err.runtimeReady === true, ...(err.runtimeReady === true ? {} : { status: 'degraded' }), lastErrorMessage: err.message });
310
432
  throw err;
311
433
  }
@@ -376,6 +498,255 @@ export class LocalAgentRuntime {
376
498
  if (this.config.runtime !== 'hermes' || !usesHermesAcp(this.config)) return Promise.resolve();
377
499
  return warmHermesAcp(this.config, this.recentAcpSessions(2)).catch(() => {});
378
500
  }
501
+ /**
502
+ * A turn this bridge ran in Hermes, so its rows are never taken for messages typed on the
503
+ * computer. A turn with no Hermes backend watched since before it began joins one quiet stretch
504
+ * (every row in it is the bridge's own), so a long time without the desktop app adds one entry.
505
+ */
506
+ rememberOwnTurn(state, { start, quietAtStart = false, text, reply, rowIds }) {
507
+ if (this.config.runtime !== 'hermes') return false;
508
+ // A new conversation starts watching at its first turn.
509
+ if (typeof state.computerTurnsThrough !== 'number') {
510
+ state.computerTurnsThrough = start;
511
+ if (quietAtStart) state.computerTurnsQuiet = true;
512
+ }
513
+ const end = Date.now() / 1000;
514
+ const turns = Array.isArray(state.ownTurns) ? state.ownTurns : [];
515
+ const quietFrom = this.watchedQuietSince();
516
+ const last = turns.at(-1);
517
+ if (quietFrom !== null && quietFrom <= start) {
518
+ if (last?.quiet && last.start >= quietFrom) last.end = end;
519
+ else turns.push({ start: quietFrom, end, quiet: true });
520
+ } else turns.push(ownTurnEntry({ start, end, text, reply, rowIds }));
521
+ // Only a backend whose reads keep failing gets here; past it the oldest could show again.
522
+ state.ownTurns = turns.slice(-KEPT_OWN_TURNS);
523
+ this.settleQuietConversation(state);
524
+ return true;
525
+ }
526
+ /** Each watcher tick: whether a Hermes backend runs. A ledger change starts a new quiet stretch. */
527
+ observeComputerBackend() {
528
+ if (hermesBackendQuietSince(this.config) === null) { this.quietSample = null; return; }
529
+ const ledger = hermesLedgerSignature(this.config);
530
+ if (this.quietSample?.ledger !== ledger) this.quietSample = { since: Date.now() / 1000, ledger };
531
+ }
532
+ /**
533
+ * Since when this bridge has watched no Hermes backend run: null unless none runs now and the
534
+ * ledger is exactly as it was then (a backend that started and stopped between two looks
535
+ * changed it). Any successful read of Hermes also clears it.
536
+ */
537
+ watchedQuietSince() {
538
+ const sample = this.quietSample;
539
+ if (!sample || hermesBackendQuietSince(this.config) === null || hermesLedgerSignature(this.config) !== sample.ledger) return null;
540
+ return sample.since;
541
+ }
542
+ /**
543
+ * With no Hermes backend run since a conversation's checkpoint, nothing on this computer could
544
+ * have written to it but this bridge (and Hermes's own CLI, by hand): the checkpoint moves to
545
+ * now and its own turns are settled without a read. That's known when this bridge has watched
546
+ * no backend run since then, or when none ran at the checkpoint (`computerTurnsQuiet`) and none
547
+ * has started since (each writes the ledger when it starts; a second's margin for coarse file
548
+ * times). True when it settled.
549
+ */
550
+ settleQuietConversation(state) {
551
+ const through = state.computerTurnsThrough;
552
+ if (typeof through !== 'number') return false;
553
+ const ledgerQuiet = hermesBackendQuietSince(this.config);
554
+ if (ledgerQuiet === null) return false;
555
+ const watched = this.watchedQuietSince();
556
+ if (!((watched !== null && watched <= through) || (state.computerTurnsQuiet === true && ledgerQuiet < through - 1))) return false;
557
+ state.computerTurnsThrough = Math.max(through, Date.now() / 1000);
558
+ state.computerTurnsQuiet = true;
559
+ delete state.computerTurnsTie;
560
+ delete state.ownTurns;
561
+ return true;
562
+ }
563
+ /** Changes whenever Hermes writes a conversation row, and when a Hermes backend starts (its ledger). */
564
+ computerTurnsSignature() {
565
+ const home = hermesProfileHome(this.config);
566
+ const files = [path.join(home, 'state.db'), path.join(home, 'state.db-wal'), path.join(this.config.hermesHome, 'spawn-ledger.json')];
567
+ return files.map((file) => { try { const stat = fs.statSync(file); return `${stat.mtimeMs}:${stat.size}`; } catch { return '-'; } }).join('|');
568
+ }
569
+ /** Conversation records with a Hermes conversation, the most recently written first (each re-read only when it changed). */
570
+ computerTurnRecords() {
571
+ const directory = path.join(this.directory, 'conversations');
572
+ let names;
573
+ try { names = fs.readdirSync(directory).filter((name) => name.endsWith('.json')); } catch { return []; }
574
+ this.recordCache ||= new Map();
575
+ const records = [];
576
+ for (const name of names) {
577
+ const file = path.join(directory, name);
578
+ let modified;
579
+ try { modified = fs.statSync(file).mtimeMs; } catch { continue; }
580
+ let cached = this.recordCache.get(name);
581
+ if (cached?.modified !== modified) {
582
+ let state;
583
+ try { state = readJson(file, null); } catch { continue; }
584
+ cached = { name, modified, state };
585
+ this.recordCache.set(name, cached);
586
+ }
587
+ const sessionId = cached.state?.runtimeSessionId || this.config.resume;
588
+ if (cached.state && Array.isArray(cached.state.messages) && sessionId) records.push({ ...cached, sessionId });
589
+ }
590
+ return records.sort((a, b) => b.modified - a.modified);
591
+ }
592
+ /** Reads each record's Hermes transcript since its checkpoint, in parallel and outside the turn queue. */
593
+ async readComputerRows(records, { timeoutMs, maxPages, chunkPages }) {
594
+ return new Map(await Promise.all(records.map(async (record) => {
595
+ const readAt = Date.now() / 1000;
596
+ try {
597
+ const read = await readHermesTranscript(this.config, record.sessionId, { after: record.state.computerTurnsThrough, skip: record.state.computerTurnsTie || [], tokens: this.hermesTokens, timeoutMs, ...(maxPages ? { maxPages } : {}), ...(chunkPages ? { chunkPages } : {}) });
598
+ if (read) this.quietSample = null; // A backend answered: it is running.
599
+ return [record.name, read ? { ...read, readAt } : { rows: null }];
600
+ } catch { return [record.name, { rows: null }]; }
601
+ })));
602
+ }
603
+ /**
604
+ * In the turn queue: applies the reads to the records, then announces what was added. With
605
+ * `quiet` (no backend running), records no backend could have written since their checkpoint
606
+ * are settled. Returns whether something was added and whether every record is up to date.
607
+ */
608
+ applyComputerReads(names, reads, readStart, { quiet = false } = {}) {
609
+ const directory = path.join(this.directory, 'conversations');
610
+ const changes = [];
611
+ let reloadAcp = false, settled = true;
612
+ for (const name of names) {
613
+ const file = path.join(directory, name);
614
+ let state;
615
+ try { state = readJson(file, null); } catch { continue; }
616
+ if (!state || !Array.isArray(state.messages) || !(state.runtimeSessionId || this.config.resume)) continue;
617
+ if (typeof state.computerTurnsThrough !== 'number') {
618
+ // Rows from before can't be told apart from this bridge's own turns: start from here.
619
+ state.computerTurnsThrough = readStart;
620
+ if (quiet) state.computerTurnsQuiet = true;
621
+ writePrivateJson(file, state);
622
+ continue;
623
+ }
624
+ if (quiet) {
625
+ if (this.settleQuietConversation(state)) writePrivateJson(file, state);
626
+ else settled = false;
627
+ continue;
628
+ }
629
+ const read = reads.get(name);
630
+ if (!read?.rows) continue;
631
+ const { added, changed } = applyComputerRows(state, read);
632
+ if (changed) writePrivateJson(file, state);
633
+ if (!added.length) continue;
634
+ reloadAcp ||= state.runtimeTransport === 'acp';
635
+ const sessionKey = state.sessionKey || this.sessionKeys.get(name);
636
+ if (sessionKey) changes.push({ sessionKey, reason: added.some((row) => row.role === 'assistant') ? 'reply' : 'message' });
637
+ }
638
+ // The warm ACP copy hasn't seen these messages; the next phone turn loads them from Hermes.
639
+ if (reloadAcp) resetHermesAcp(this.config);
640
+ for (const change of changes) {
641
+ try { this.onConversationChanged?.(change); } catch { /* A missed update only costs a refresh. */ }
642
+ }
643
+ return { added: changes.length > 0, settled };
644
+ }
645
+ /**
646
+ * Started when a phone or web turn arrives, before it queues: reads this conversation's computer
647
+ * messages, so they can go in first. Resolves to the read to apply, or null; never rejects.
648
+ * After a failed read it is skipped for 30 s (the watcher catches up instead).
649
+ */
650
+ async readCatchUp(sessionKey) {
651
+ try {
652
+ if (this.config.runtime !== 'hermes' || !this.config.hermesHome || Date.now() < (this.catchUpPausedUntil || 0)) return null;
653
+ if (this.computerTurnsSettled === this.computerTurnsSignature()) return null;
654
+ const name = path.basename(this.file(sessionKey));
655
+ const record = this.computerTurnRecords().find((entry) => entry.name === name);
656
+ if (!record || typeof record.state.computerTurnsThrough !== 'number') return null;
657
+ const readStart = Date.now() / 1000;
658
+ const reads = await this.readComputerRows([record], { timeoutMs: 5000 });
659
+ if (!reads.get(name)?.rows) {
660
+ if (hermesBackendQuietSince(this.config) === null) this.catchUpPausedUntil = Date.now() + 30000;
661
+ return null;
662
+ }
663
+ return { name, reads, readStart };
664
+ } catch { return null; }
665
+ }
666
+ /**
667
+ * One look for messages typed on this computer. Hermes is read outside the turn queue, and only
668
+ * for conversations it changed since their checkpoint, plus the `recent` most recently written
669
+ * (in case Hermes moved one to a new id) and, when the session list was too long to finish, the
670
+ * unlisted ones in turn. At most 25 are read per look; only applying the result waits for a phone
671
+ * turn. False when it should be tried again (soon when a read made progress but isn't done).
672
+ */
673
+ async importComputerTurns({ timeoutMs = 30000, recent = 3, maxPages, chunkPages, listPages } = {}) {
674
+ if (this.config.runtime !== 'hermes' || !this.config.hermesHome) return true;
675
+ const signature = this.computerTurnsSignature();
676
+ const readStart = Date.now() / 1000;
677
+ const records = this.computerTurnRecords();
678
+ const watched = records.filter((record) => typeof record.state.computerTurnsThrough === 'number');
679
+ let complete = true, quiet = false;
680
+ let reads = new Map();
681
+ this.computerTurnsBackend = true;
682
+ this.computerTurnsProgress = false;
683
+ if (watched.length) {
684
+ this.knownThrough ||= new Map();
685
+ this.lastRead ||= new Map();
686
+ // Until when a conversation is known to have nothing new: its checkpoint, or its last read or listing.
687
+ const known = (record) => Math.max(record.state.computerTurnsThrough, this.knownThrough.get(record.sessionId) ?? 0);
688
+ let listing;
689
+ try { listing = await readHermesActivity(this.config, { since: Math.min(...watched.map(known)), tokens: this.hermesTokens, ...(listPages ? { maxPages: listPages } : {}) }); } catch { listing = undefined; complete = false; }
690
+ if (listing === null) {
691
+ // No Hermes backend is running: settle what none could have changed, wait for one for the rest.
692
+ quiet = true;
693
+ this.computerTurnsBackend = false;
694
+ } else {
695
+ if (listing) this.quietSample = null;
696
+ const changed = [], unlisted = [];
697
+ for (const record of watched) {
698
+ const at = listing?.activity.get(record.sessionId);
699
+ // Not listed: it changed no later than the oldest listed (or, with no list, it may have).
700
+ const latest = at ?? (listing?.complete ? 0 : listing?.oldest ?? Infinity);
701
+ if (latest <= known(record)) this.knownThrough.set(record.sessionId, readStart);
702
+ else (at !== undefined ? changed : unlisted).push(record);
703
+ }
704
+ // Unlisted ones (a list too long to finish, or no list) are read in turns, least recently first.
705
+ unlisted.sort((a, b) => (this.lastRead.get(a.name) ?? 0) - (this.lastRead.get(b.name) ?? 0));
706
+ const due = [...new Set([...changed, ...watched.slice(0, recent), ...unlisted])];
707
+ if (due.length > MAX_READS_PER_LOOK) complete = false;
708
+ const reading = due.slice(0, MAX_READS_PER_LOOK);
709
+ reads = await this.readComputerRows(reading, { timeoutMs, maxPages, chunkPages });
710
+ for (const record of reading) {
711
+ const read = reads.get(record.name);
712
+ this.lastRead.set(record.name, Date.now());
713
+ if (!read?.rows) complete = false;
714
+ else if (read.covered === false) { complete = false; this.computerTurnsProgress = true; }
715
+ else this.knownThrough.set(record.sessionId, Math.max(read.readAt, listing?.activity.get(record.sessionId) ?? 0));
716
+ }
717
+ }
718
+ }
719
+ const apply = this.queue.then(() => this.applyComputerReads(records.map((record) => record.name), reads, readStart, { quiet }));
720
+ this.queue = apply.catch(() => {});
721
+ const { settled } = await apply;
722
+ if (quiet && !settled) complete = false;
723
+ if (complete) this.computerTurnsSettled = signature;
724
+ return complete;
725
+ }
726
+ /**
727
+ * Messages the person types to the persona on this computer (in Hermes desktop, or in oomi's
728
+ * Talk while it shows this conversation) join the conversation's record, so the phone and the
729
+ * web show them. Watches Hermes's state.db and backend ledger, and whether a backend runs; a look
730
+ * that isn't done is tried again: in a second while it is making progress, every 10 s while a
731
+ * backend runs, every 30 s while none does.
732
+ */
733
+ watchComputerTurns({ intervalMs = 1000, progressMs = 1000, retryMs = 10000, idleRetryMs = 30000 } = {}) {
734
+ if (this.config.runtime !== 'hermes' || !this.config.hermesHome) return () => {};
735
+ let seen = '', dirty = false, running = false, retryAt = 0;
736
+ const tick = () => {
737
+ this.observeComputerBackend();
738
+ const now = this.computerTurnsSignature();
739
+ if (now !== seen) { seen = now; dirty = true; retryAt = 0; }
740
+ if (!dirty || running || Date.now() < retryAt) return;
741
+ dirty = false; running = true;
742
+ const retry = () => { dirty = true; retryAt = Date.now() + (this.computerTurnsProgress ? progressMs : this.computerTurnsBackend === false ? idleRetryMs : retryMs); };
743
+ this.importComputerTurns().then((complete) => { if (!complete) retry(); }, retry).finally(() => { running = false; });
744
+ };
745
+ const timer = setInterval(tick, intervalMs);
746
+ timer.unref?.();
747
+ tick();
748
+ return () => clearInterval(timer);
749
+ }
379
750
  recentAcpSessions(limit) {
380
751
  const directory = path.join(this.directory, 'conversations');
381
752
  let files;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oomi-ai",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Connect OpenClaw, Hermes, Grok Bot, and other agents to Oomi with verified runtime adapters",
5
5
  "bin": {
6
6
  "oomi": "bin/oomi-ai.js"