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.
package/lib/localAgent.js CHANGED
@@ -4,8 +4,9 @@ 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';
8
- import { runHermesAcpTurn, hermesAcpAvailable, resetHermesAcp, warmHermesAcp, hermesAcpModelReport } from './hermesAcp.js';
7
+ import { runSharedHermesTurn, hermesRefusal, readHermesTranscript, readHermesActivity, hermesTranscriptTurns, hermesProfileHome, hermesBackendQuietSince, hermesLedgerSignature, rowKey } from './hermesGateway.js';
8
+ import { runHermesAcpTurn, hermesAcpAvailable, resetHermesAcp, warmHermesAcp, hermesAcpModels, setHermesAcpModel, continuityPreamble } from './hermesAcp.js';
9
+ import { CHAT_MODELS_CAPABILITY, ChatModelsError, hermesEntries, matchModel, modelChoice, modelsAnswer } from './chatModels.js';
9
10
  import { grokbotConfig, runGrokbotTurn, completedGrokbotTurn } from './grokbotRuntime.js';
10
11
  import { classifyRuntimeFailure } from './runtimeFailure.js';
11
12
 
@@ -73,6 +74,104 @@ export function readJson(file, fallback = {}) {
73
74
  }
74
75
  }
75
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
+
76
175
  export function localAgentConfig(flags) {
77
176
  const runtime = String(flags.runtime || '');
78
177
  if (runtime === 'grokbot') return grokbotConfig(flags, flags.connectionDirectory);
@@ -114,9 +213,19 @@ function usesHermesAcp(config) {
114
213
  return config.hermesTransport === 'acp' || hermesAcpAvailable(config);
115
214
  }
116
215
 
216
+ // A guest's turn (agent channels, chat links) runs with the persona's tools off: Hermes as
217
+ // `hermes chat --toolsets clarify` (no terminal, files, browser, memory, skills or MCP servers;
218
+ // Hermes freezes the toolsets into the session), a command adapter told `sandbox: true`. Grok
219
+ // Bot can't be limited, so it doesn't take guests.
220
+ export const SANDBOX_TOOLSETS = 'clarify';
221
+
117
222
  // No shell interpolation. Message bodies travel over stdin, never as executable code.
118
223
  export async function runLocalAgent(config, request, options = {}) {
224
+ if (request.sandbox && config.runtime === 'grokbot') {
225
+ throw Object.assign(new Error("This persona's runtime can't answer guests with its tools turned off."), { notStarted: true, runtimeFailureCode: 'guest_sandbox_unavailable' });
226
+ }
119
227
  if (config.runtime === 'grokbot') return runGrokbotTurn(config, request, options);
228
+ if (config.runtime === 'hermes' && request.sandbox) return runAgentProcess(config, request, options);
120
229
  if (config.runtime === 'hermes') {
121
230
  const shared = await runSharedHermesTurn(config, request, options);
122
231
  if (shared) {
@@ -151,6 +260,7 @@ function runAgentProcess(config, request, { signal, timeoutMs = 180000 } = {}) {
151
260
  if (config.runtime === 'hermes') {
152
261
  if (config.profile) args.push('--profile', config.profile);
153
262
  args.push('chat', '--quiet', '--query-file', '-');
263
+ if (request.sandbox) args.push('--toolsets', SANDBOX_TOOLSETS);
154
264
  if (request.runtimeSessionId) args.push('--resume', request.runtimeSessionId);
155
265
  if (request.imagePaths?.[0]) args.push('--image', request.imagePaths[0]);
156
266
  }
@@ -220,15 +330,19 @@ export class LocalAgentRuntime {
220
330
  this.queue = Promise.resolve();
221
331
  this.active = new Map();
222
332
  this.deliveries = 0;
223
- // Told what models the runtime offers for a call's faster model, when that changes.
224
- this.onModels = null;
225
- this.lastModelReport = '';
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();
226
338
  }
227
339
  file(sessionKey) { return path.join(this.directory, 'conversations', createHash('sha256').update(sessionKey).digest('hex') + '.json'); }
228
- history(sessionKey) { return readJson(this.file(sessionKey), { messages: [], receipts: {} }); }
229
- async turn({ sessionKey, message, idempotencyKey, attachments = [], retryInterrupted = false, onText, onStarted, oomi }) {
230
- // A call turn names the persona's faster model (Oomi's call.model); see applyCallModel.
231
- const callModel = typeof oomi?.call?.model === 'string' && oomi.call.model.trim().length <= 200 ? oomi.call.model.trim() : '';
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
+ }
345
+ async turn({ sessionKey, message, idempotencyKey, attachments = [], retryInterrupted = false, onText, onStarted, oomi, sandbox = false }) {
232
346
  const images = readImageAttachments(attachments);
233
347
  const text = typeof message === 'string' ? message : '';
234
348
  if (typeof sessionKey !== 'string' || !sessionKey || typeof idempotencyKey !== 'string' || !idempotencyKey || (!text.trim() && !images.length)) throw new Error('A session, message, and idempotency key are required.');
@@ -244,8 +358,10 @@ export class LocalAgentRuntime {
244
358
  }
245
359
  const receiptKey = createHash('sha256').update(idempotencyKey).digest('hex');
246
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);
247
363
  const promise = this.queue.then(async () => {
248
- const state = this.history(sessionKey);
364
+ let state = this.history(sessionKey);
249
365
  const previous = state.receipts[receiptKey];
250
366
  if (previous?.message !== undefined && previous.message !== message) throw new Error('Idempotency key was reused for a different message.');
251
367
  if (previous && (previous.practiceDigest || null) !== practiceDigest) throw new Error('Idempotency key was reused for different practice context.');
@@ -255,8 +371,16 @@ export class LocalAgentRuntime {
255
371
  const resumedReply = previous && this.config.runtime === 'grokbot' ? completedGrokbotTurn(this.config, { sessionKey, message: prompt, idempotencyKey, runtimeSessionId: state.runtimeSessionId || this.config.resume }) : null;
256
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.');
257
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
+ }
258
379
  state.receipts[receiptKey] = { message, practiceDigest, status: 'running' };
259
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;
260
384
  let scratch;
261
385
  let started = previous?.status === 'started';
262
386
  const confirmStarted = () => {
@@ -269,27 +393,41 @@ export class LocalAgentRuntime {
269
393
  };
270
394
  try {
271
395
  scratch = images.length ? writeTurnImages(images) : null;
272
- const result = resumedReply || await runLocalAgent(this.config, { sessionKey, message: prompt, idempotencyKey, history: state.messages, runtimeSessionId: state.runtimeSessionId || this.config.resume, runtimeTransport: state.runtimeTransport, imagePaths: scratch?.paths || [], callModel, chatModel: state.runtimeChatModel || null }, { signal: controller.signal, onText: text => { confirmStarted(); onText?.(text); }, onStarted: confirmStarted });
396
+ // A sandboxed turn keeps its own runtime session (its tools are frozen off), started with
397
+ // the conversation so far; the conversation's own session is left as it is.
398
+ const request = sandbox
399
+ ? { sessionKey, message: (state.sandboxSessionId ? '' : continuityPreamble(state.messages)) + prompt, idempotencyKey, history: state.messages, runtimeSessionId: state.sandboxSessionId || '', runtimeTransport: 'cli', imagePaths: [], sandbox: true }
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 };
401
+ const result = resumedReply || await runLocalAgent(this.config, request, { signal: controller.signal, onText: text => { confirmStarted(); onText?.(text); }, onStarted: confirmStarted });
273
402
  confirmStarted();
274
- state.runtimeSessionId = result.sessionId;
275
- if (result.transport) state.runtimeTransport = result.transport;
276
- // While the session is on a call's model, the model to go back to (kept here, so a
277
- // restart still restores it before the next chat turn).
278
- if ('chatModel' in result) {
403
+ state.sessionKey = sessionKey;
404
+ if (sandbox) {
405
+ if (result.sessionId) state.sandboxSessionId = result.sessionId;
406
+ } else {
407
+ state.runtimeSessionId = result.sessionId;
408
+ if (result.transport) state.runtimeTransport = result.transport;
409
+ delete state.runtimeSeedPending;
410
+ }
411
+ // A session an older bridge left on a call's model keeps the model to go back to until
412
+ // Hermes has switched it (restoreChatModel).
413
+ if (!sandbox && 'chatModel' in result) {
279
414
  if (result.chatModel) state.runtimeChatModel = result.chatModel;
280
415
  else delete state.runtimeChatModel;
281
416
  }
282
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);
283
420
  state.receipts[receiptKey] = { message, practiceDigest, result };
421
+ keepRecentReceipts(state);
284
422
  writePrivateJson(this.file(sessionKey), state);
285
423
  this.onHealth({ runtimeReady: true, lastReplyAt: new Date().toISOString(), lastErrorMessage: '' });
286
- this.reportModels(state.runtimeChatModel);
287
424
  return { ...result, started: true };
288
425
  } catch (err) {
289
- if (err.notStarted === true && !started) {
290
- state.receipts[receiptKey] = { message, practiceDigest, status: 'not_started' };
291
- writePrivateJson(this.file(sessionKey), state);
292
- }
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);
293
431
  this.onHealth({ runtimeReady: err.runtimeReady === true, ...(err.runtimeReady === true ? {} : { status: 'degraded' }), lastErrorMessage: err.message });
294
432
  throw err;
295
433
  }
@@ -306,32 +444,308 @@ export class LocalAgentRuntime {
306
444
  }
307
445
  socket() { return new LocalAgentSocket(this); }
308
446
  close() { if (this.config.runtime === 'hermes') resetHermesAcp(this.config); }
447
+ /** What this runtime adds to the bridge's capabilities on connect. */
448
+ capabilities() { return this.switchesModels() ? [CHAT_MODELS_CAPABILITY] : []; }
449
+ switchesModels() { return this.config.runtime === 'hermes' && usesHermesAcp(this.config); }
450
+ answering(sessionKey) { return [...this.active.values()].some((entry) => entry.sessionKey === sessionKey); }
451
+ /** `/model` in Talk (docs/specs/chat-models-v1.md): the conversation's model and what it can switch to. */
452
+ async models(sessionKey) {
453
+ if (!this.switchesModels() || typeof sessionKey !== 'string' || !sessionKey) throw new ChatModelsError('unavailable');
454
+ // Mid-turn the conversation's session belongs to the turn: read, don't open one.
455
+ const answering = this.answering(sessionKey);
456
+ const result = await hermesAcpModels(this.config, this.acpSession(sessionKey), { create: answering ? false : 'if-unknown' }).catch(() => { throw new ChatModelsError('unavailable'); });
457
+ if (!answering) this.keepAcpSession(sessionKey, result.session);
458
+ return modelsAnswer({ current: result.current, entries: hermesEntries(result.available) });
459
+ }
460
+ /** Switches this conversation only; nothing reaches the model, and the persona's default stays. */
461
+ async setModel(sessionKey, model) {
462
+ if (!this.switchesModels() || typeof sessionKey !== 'string' || !sessionKey) throw new ChatModelsError('unavailable');
463
+ if (typeof model !== 'string' || !model.trim() || model.length > 300) throw new ChatModelsError('unknown_model');
464
+ if (this.answering(sessionKey)) throw new ChatModelsError('busy');
465
+ // Names resolve against Hermes's list; a new conversation's session is opened (and kept) to learn it.
466
+ const listed = await hermesAcpModels(this.config, this.acpSession(sessionKey), { create: 'if-unknown' }).catch(() => ({ session: null, available: [] }));
467
+ this.keepAcpSession(sessionKey, listed.session);
468
+ let result;
469
+ try {
470
+ result = await setHermesAcpModel(this.config, this.acpSession(sessionKey), matchModel(model, hermesEntries(listed.available)));
471
+ } catch (err) {
472
+ throw new ChatModelsError(err.code === 'hermes_busy' ? 'busy' : err.code === 'hermes_unknown_model' ? 'unknown_model' : 'unavailable');
473
+ }
474
+ this.keepAcpSession(sessionKey, result.session, { picked: true });
475
+ return { scope: 'conversation', current: modelChoice(result.current, hermesEntries(result.available)) };
476
+ }
477
+ acpSession(sessionKey) {
478
+ const state = this.history(sessionKey);
479
+ return state.runtimeTransport === 'acp' && state.runtimeSessionId ? state.runtimeSessionId : '';
480
+ }
481
+ /** A session `/model` opened is the conversation's from now on; one made for a conversation with history still needs its seed. */
482
+ keepAcpSession(sessionKey, session, { picked = false } = {}) {
483
+ if (!session) return;
484
+ const state = this.history(sessionKey);
485
+ const changed = state.runtimeSessionId !== session.sessionId || state.runtimeTransport !== 'acp';
486
+ if (!changed && !(picked && state.runtimeChatModel)) return;
487
+ if (changed) {
488
+ state.runtimeSessionId = session.sessionId;
489
+ state.runtimeTransport = 'acp';
490
+ if (session.created && state.messages.length) state.runtimeSeedPending = true;
491
+ }
492
+ // The person's pick wins over a call model an older bridge meant to undo.
493
+ if (picked) delete state.runtimeChatModel;
494
+ writePrivateJson(this.file(sessionKey), state);
495
+ }
309
496
  /** Gets Hermes ready before a message arrives: at bridge start and when a call opens. */
310
497
  warm() {
311
498
  if (this.config.runtime !== 'hermes' || !usesHermesAcp(this.config)) return Promise.resolve();
312
- return warmHermesAcp(this.config, this.recentAcpSessions(2)).then(() => this.reportModels(), () => {});
313
- }
314
- /** Tells onModels what the runtime offers for calls, once Hermes has said and whenever it changes. */
315
- reportModels(chatModel = '') {
316
- if (!this.onModels || this.config.runtime !== 'hermes') return;
317
- const report = hermesAcpModelReport(this.config, { chatModel: chatModel || this.rememberedChatModel() });
318
- if (!report) return;
319
- const text = JSON.stringify(report);
320
- if (text === this.lastModelReport) return;
321
- this.lastModelReport = text;
322
- // Reporting never breaks a turn; a report that didn't arrive goes again after the next one.
323
- Promise.resolve().then(() => this.onModels(report)).then((delivered) => { if (delivered === false) this.lastModelReport = ''; }, () => { this.lastModelReport = ''; });
324
- }
325
- /** A conversation on a call's model knows what the persona chats with. */
326
- rememberedChatModel() {
499
+ return warmHermesAcp(this.config, this.recentAcpSessions(2)).catch(() => {});
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() {
327
571
  const directory = path.join(this.directory, 'conversations');
328
- let files;
329
- try { files = fs.readdirSync(directory).filter((name) => name.endsWith('.json')); } catch { return ''; }
330
- for (const name of files) {
331
- const state = readJson(path.join(directory, name), {});
332
- if (typeof state.runtimeChatModel === 'string' && state.runtimeChatModel) return state.runtimeChatModel;
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 });
333
589
  }
334
- return '';
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);
335
749
  }
336
750
  recentAcpSessions(limit) {
337
751
  const directory = path.join(this.directory, 'conversations');
@@ -370,12 +784,16 @@ class LocalAgentSocket extends EventEmitter {
370
784
  try { req = JSON.parse(raw); } catch { return; }
371
785
  if (req.type !== 'req') return;
372
786
  const reply = (payload) => this.frame({ type: 'res', id: req.id, ok: true, payload });
373
- const fail = (message) => this.frame({ type: 'res', id: req.id, ok: false, error: { code: 'local_agent_error', message } });
787
+ const fail = (message, code = 'local_agent_error') => this.frame({ type: 'res', id: req.id, ok: false, error: { code, message } });
374
788
  const params = req.params || {};
375
789
  if (req.method === 'connect') { this.connected = true; return reply({ type: 'hello-ok', protocol: 3, features: { methods: ['chat.send', 'chat.history', 'chat.abort'], events: ['chat'] }, snapshot: {}, policy: { tickIntervalMs: 30000 } }); }
376
790
  if (!this.connected) return fail('Connect before sending requests.');
377
791
  if (req.method === 'chat.history') return reply({ sessionKey: params.sessionKey, messages: this.runtime.history(params.sessionKey || '').messages.slice(-Math.min(params.limit || 200, 500)) });
378
792
  if (req.method === 'chat.abort') return reply({ aborted: this.runtime.abort(params.sessionKey, params.runId) });
793
+ // `/model` in Talk (docs/specs/chat-models-v1.md).
794
+ const failModels = (err) => fail(err instanceof ChatModelsError ? err.message : new ChatModelsError('unavailable').message, err instanceof ChatModelsError ? err.code : 'unavailable');
795
+ if (req.method === 'oomi.models.list') return void this.runtime.models(params.sessionKey).then(reply, failModels);
796
+ if (req.method === 'oomi.models.set') return void this.runtime.setModel(params.sessionKey, params.model).then(reply, failModels);
379
797
  if (req.method !== 'chat.send') return fail(`Method ${req.method} is not supported by this agent adapter.`);
380
798
  const runId = params.idempotencyKey || req.id || randomUUID();
381
799
  reply({ runId, status: 'started' });