oomi-ai 0.15.0 → 0.16.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 +11 -0
- package/bin/oomi-ai.js +142 -13
- package/lib/bridgeMaintenance.js +2 -2
- package/lib/bridgeService.js +73 -7
- package/lib/controlCommand.js +252 -0
- package/lib/hermesAcp.js +134 -10
- package/lib/localAgent.js +69 -17
- package/lib/processSupervisor.js +11 -3
- package/lib/processTable.js +62 -18
- package/lib/windowHost.js +1215 -0
- package/lib/windowHostManifest.json +8 -0
- package/lib/windowPolicy.js +237 -0
- package/lib/windowsCommand.js +299 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +16 -9
- package/skills/oomi/SKILL.md +35 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// `oomi control …`: the person at the computer lets their personas operate it for them (click,
|
|
2
|
+
// type, press keys, bring a window forward), so "play me some music" asked from a phone or a
|
|
3
|
+
// headset ends with the music playing, not with a refusal nobody is there to answer.
|
|
4
|
+
//
|
|
5
|
+
// A persona's turn from oomi has nobody at the computer to answer its runtime's approval prompt.
|
|
6
|
+
// Hermes then refuses each desktop action it has no standing grant for, one kind at a time: a
|
|
7
|
+
// person who once chose "always" for a click still has typing and double-clicking refused. `on`
|
|
8
|
+
// gives Hermes that standing grant for every desktop action, in Hermes's own allow list
|
|
9
|
+
// (`command_allowlist`, the list its "always" answer writes), and nothing wider: commands Hermes
|
|
10
|
+
// calls dangerous are still refused. `on` is confirmed here with Windows Hello, as `oomi windows
|
|
11
|
+
// on` is, so a persona's agent, which runs these commands too, can't give itself control. `off`
|
|
12
|
+
// takes back exactly what `on` added and never asks.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { computerDirectory } from './windowPolicy.js';
|
|
17
|
+
import { confirmAtComputer } from './windowsCommand.js';
|
|
18
|
+
import { resolveWindowHelper } from './windowHost.js';
|
|
19
|
+
import { readJson, writePrivateJson } from './localAgent.js';
|
|
20
|
+
import { hermesProfileHome } from './hermesGateway.js';
|
|
21
|
+
|
|
22
|
+
export const HOW_TO_ENABLE_CONTROL = 'On this computer, open a terminal and run: oomi control on';
|
|
23
|
+
|
|
24
|
+
// Hermes asks before each of these (tools/computer_use: every action that changes what is on
|
|
25
|
+
// screen), once for input delivered to a window in the background and once for input that
|
|
26
|
+
// brings the window forward. Looking (capture, list_apps, list_windows, wait) never asks.
|
|
27
|
+
export const DESKTOP_ACTIONS = Object.freeze(['click', 'double_click', 'right_click', 'middle_click', 'drag', 'scroll', 'type', 'key', 'set_value', 'focus_app', 'bring_to_front']);
|
|
28
|
+
export const hermesDesktopGrants = () => DESKTOP_ACTIONS.flatMap((action) => [`cua:${action}:background`, `cua:${action}:foreground`]);
|
|
29
|
+
|
|
30
|
+
const USAGE = `oomi control on let your personas click and type on this computer when you ask them from oomi (Windows Hello)
|
|
31
|
+
oomi control off take that back
|
|
32
|
+
oomi control status [--json]`;
|
|
33
|
+
|
|
34
|
+
export const controlPath = (directory = computerDirectory()) => path.join(directory, 'control.json');
|
|
35
|
+
|
|
36
|
+
export function readControl(directory = computerDirectory()) {
|
|
37
|
+
let saved = null;
|
|
38
|
+
try { saved = readJson(controlPath(directory), null); } catch { saved = null; }
|
|
39
|
+
const runtimes = Array.isArray(saved?.runtimes) ? saved.runtimes.filter((entry) => entry && typeof entry.config === 'string' && Array.isArray(entry.added)) : [];
|
|
40
|
+
return {
|
|
41
|
+
version: 1,
|
|
42
|
+
enabled: saved?.enabled === true,
|
|
43
|
+
confirmedAt: typeof saved?.confirmedAt === 'string' ? saved.confirmedAt : null,
|
|
44
|
+
confirmedWith: typeof saved?.confirmedWith === 'string' ? saved.confirmedWith : null,
|
|
45
|
+
runtimes: runtimes.map((entry) => ({ runtime: 'hermes', connection: String(entry.connection || ''), config: entry.config, added: entry.added.filter((key) => typeof key === 'string') })),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The Hermes personas linked on this computer, one entry per Hermes config file. */
|
|
50
|
+
export function hermesConnections(env = process.env) {
|
|
51
|
+
const root = String(env.OOMI_CONNECTIONS_DIR || '').trim() || path.join(os.homedir(), '.oomi', 'connections');
|
|
52
|
+
let names = [];
|
|
53
|
+
try { names = fs.readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(); } catch { names = []; }
|
|
54
|
+
const found = new Map();
|
|
55
|
+
for (const name of names) {
|
|
56
|
+
let state = null;
|
|
57
|
+
try { state = readJson(path.join(root, name, 'oomi-bridge.json'), null); } catch { state = null; }
|
|
58
|
+
const agent = state?.localAgent;
|
|
59
|
+
if (agent?.runtime !== 'hermes' || typeof agent.hermesHome !== 'string' || !agent.hermesHome) continue;
|
|
60
|
+
const config = path.join(hermesProfileHome(agent), 'config.yaml');
|
|
61
|
+
if (!found.has(config.toLowerCase())) found.set(config.toLowerCase(), { runtime: 'hermes', connection: name, config });
|
|
62
|
+
}
|
|
63
|
+
return [...found.values()];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// --- Hermes's allow list -------------------------------------------------------------------
|
|
67
|
+
// config.yaml is the person's own file, written by Hermes: only the `command_allowlist` list is
|
|
68
|
+
// touched, in the block form Hermes writes, and anything else there is left byte for byte. A
|
|
69
|
+
// list in a form this doesn't know is refused, not rewritten.
|
|
70
|
+
|
|
71
|
+
const KEY_LINE = /^command_allowlist:[ \t]*(.*)$/;
|
|
72
|
+
const ITEM_LINE = /^([ \t]*)-[ \t]+(.*)$/;
|
|
73
|
+
|
|
74
|
+
function unquote(text) {
|
|
75
|
+
const value = text.replace(/[ \t]+#.*$/, '').trim();
|
|
76
|
+
if (/^'.*'$/.test(value)) return value.slice(1, -1).replace(/''/g, "'");
|
|
77
|
+
if (/^".*"$/.test(value)) { try { return JSON.parse(value); } catch { return null; } }
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Where the list is in the file and what it holds. `form`: absent | empty | block | unknown. */
|
|
82
|
+
export function readAllowlist(text) {
|
|
83
|
+
const newline = text.includes('\r\n') ? '\r\n' : '\n';
|
|
84
|
+
const lines = text.split(/\r?\n/);
|
|
85
|
+
const at = lines.findIndex((line) => KEY_LINE.test(line));
|
|
86
|
+
if (at < 0) return { form: 'absent', items: [], lines, newline };
|
|
87
|
+
const rest = lines[at].match(KEY_LINE)[1].replace(/[ \t]*#.*$/, '').trim();
|
|
88
|
+
if (rest === '[]') return { form: 'empty', items: [], lines, newline, at, end: at + 1, indent: ' ' };
|
|
89
|
+
if (rest !== '') return { form: 'unknown', items: [], lines, newline };
|
|
90
|
+
const items = [];
|
|
91
|
+
let end = at + 1;
|
|
92
|
+
let indent = null;
|
|
93
|
+
for (; end < lines.length; end += 1) {
|
|
94
|
+
const match = lines[end].match(ITEM_LINE);
|
|
95
|
+
if (!match || (indent !== null && match[1] !== indent)) break;
|
|
96
|
+
const value = unquote(match[2]);
|
|
97
|
+
// A list of anything but plain strings (a nested map, a multi-line string) isn't Hermes's.
|
|
98
|
+
if (value === null || value === '' || /^[\[{|>&*!]/.test(value)) return { form: 'unknown', items: [], lines, newline };
|
|
99
|
+
indent = match[1];
|
|
100
|
+
items.push(value);
|
|
101
|
+
}
|
|
102
|
+
// A following line indented deeper than the list belongs to something this didn't read.
|
|
103
|
+
if (end < lines.length && indent !== null && /^[ \t]+\S/.test(lines[end]) && lines[end].match(/^[ \t]*/)[0].length > indent.length) return { form: 'unknown', items: [], lines, newline };
|
|
104
|
+
return { form: items.length ? 'block' : 'empty', items, lines, newline, at, end, indent: indent ?? ' ' };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const plain = (key) => (/^[A-Za-z0-9_][A-Za-z0-9_:.-]*$/.test(key) ? key : JSON.stringify(key));
|
|
108
|
+
|
|
109
|
+
/** The file's text with `add` in the list and `remove` out of it; null when nothing changes. */
|
|
110
|
+
export function editAllowlist(text, { add = [], remove = [] } = {}) {
|
|
111
|
+
const list = readAllowlist(text);
|
|
112
|
+
if (list.form === 'unknown') throw new Error("Hermes's command_allowlist isn't a plain list, so oomi left it alone.");
|
|
113
|
+
const dropped = new Set(remove);
|
|
114
|
+
const kept = list.items.filter((item) => !dropped.has(item));
|
|
115
|
+
const wanted = [...kept, ...add.filter((key) => !kept.includes(key) && !dropped.has(key))];
|
|
116
|
+
if (wanted.length === list.items.length && wanted.every((item, index) => item === list.items[index])) return null;
|
|
117
|
+
const lines = [...list.lines];
|
|
118
|
+
if (list.form === 'absent') {
|
|
119
|
+
if (wanted.length === 0) return null;
|
|
120
|
+
while (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
121
|
+
lines.push('command_allowlist:', ...wanted.map((item) => ` - ${plain(item)}`), '');
|
|
122
|
+
return lines.join(list.newline);
|
|
123
|
+
}
|
|
124
|
+
// Lines the person wrote stay as they wrote them; new ones are added after them.
|
|
125
|
+
const original = lines.slice(list.at + 1, list.end);
|
|
126
|
+
const keptLines = original.filter((line, index) => !dropped.has(list.items[index]));
|
|
127
|
+
const added = wanted.slice(kept.length).map((item) => `${list.indent}- ${plain(item)}`);
|
|
128
|
+
const body = [...keptLines, ...added];
|
|
129
|
+
lines.splice(list.at, list.end - list.at, ...(body.length ? ['command_allowlist:', ...body] : ['command_allowlist: []']));
|
|
130
|
+
return lines.join(list.newline);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function writeConfig(file, text) {
|
|
134
|
+
const temporary = `${file}.oomi-${process.pid}.tmp`;
|
|
135
|
+
fs.writeFileSync(temporary, text, { mode: 0o600 });
|
|
136
|
+
fs.renameSync(temporary, file);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Adds the desktop grants to one Hermes config. Returns the keys this call added. */
|
|
140
|
+
export function grantHermesDesktop(config, { backup = true } = {}) {
|
|
141
|
+
const text = fs.readFileSync(config, 'utf8');
|
|
142
|
+
const before = readAllowlist(text);
|
|
143
|
+
const edited = editAllowlist(text, { add: hermesDesktopGrants() });
|
|
144
|
+
if (edited === null) return [];
|
|
145
|
+
if (backup) {
|
|
146
|
+
const copy = `${config}.before-oomi-control.bak`;
|
|
147
|
+
if (!fs.existsSync(copy)) fs.copyFileSync(config, copy);
|
|
148
|
+
}
|
|
149
|
+
writeConfig(config, edited);
|
|
150
|
+
const had = new Set(before.items);
|
|
151
|
+
return hermesDesktopGrants().filter((key) => !had.has(key));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Takes back the keys `on` added; grants the person gave Hermes themselves stay. */
|
|
155
|
+
export function revokeHermesDesktop(config, added) {
|
|
156
|
+
let text;
|
|
157
|
+
try { text = fs.readFileSync(config, 'utf8'); } catch (err) { if (err.code === 'ENOENT') return false; throw err; }
|
|
158
|
+
const edited = editAllowlist(text, { remove: added });
|
|
159
|
+
if (edited === null) return false;
|
|
160
|
+
writeConfig(config, edited);
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** What each linked persona may do on this computer right now, read from its runtime. */
|
|
165
|
+
export function controlStatus({ directory = computerDirectory(), env = process.env } = {}) {
|
|
166
|
+
const control = readControl(directory);
|
|
167
|
+
const personas = hermesConnections(env).map((entry) => {
|
|
168
|
+
let granted = [];
|
|
169
|
+
let readable = true;
|
|
170
|
+
try { const list = readAllowlist(fs.readFileSync(entry.config, 'utf8')); readable = list.form !== 'unknown'; granted = list.items; } catch { readable = false; }
|
|
171
|
+
const missing = hermesDesktopGrants().filter((key) => !granted.includes(key));
|
|
172
|
+
return { ...entry, readable, canControl: readable && missing.length === 0, missing };
|
|
173
|
+
});
|
|
174
|
+
return {
|
|
175
|
+
enabled: control.enabled,
|
|
176
|
+
confirmedAt: control.confirmedAt,
|
|
177
|
+
confirmedWith: control.confirmedWith,
|
|
178
|
+
personas,
|
|
179
|
+
...(control.enabled ? {} : { howToEnable: HOW_TO_ENABLE_CONTROL }),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function describeStatus(value) {
|
|
184
|
+
const lines = [`Computer control: ${value.enabled ? 'on' : 'off'}`];
|
|
185
|
+
if (value.personas.length === 0) lines.push('No Hermes persona is linked on this computer.');
|
|
186
|
+
for (const persona of value.personas) {
|
|
187
|
+
if (!persona.readable) lines.push(`${persona.connection}: oomi couldn't read its Hermes allow list (${persona.config}).`);
|
|
188
|
+
else if (persona.canControl) lines.push(`${persona.connection}: can click, type and press keys here.`);
|
|
189
|
+
else lines.push(`${persona.connection}: Hermes still refuses ${[...new Set(persona.missing.map((key) => key.split(':')[1]))].join(', ')}.`);
|
|
190
|
+
}
|
|
191
|
+
if (!value.enabled) lines.push(HOW_TO_ENABLE_CONTROL);
|
|
192
|
+
return lines.join('\n');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export async function handleControlCommand(subcommand = 'status', flags = {}, _positionals = [], {
|
|
196
|
+
directory = computerDirectory(),
|
|
197
|
+
env = process.env,
|
|
198
|
+
platform = process.platform,
|
|
199
|
+
resolveHelper = () => resolveWindowHelper({ env, platform }),
|
|
200
|
+
confirm = confirmAtComputer,
|
|
201
|
+
print = (text) => console.log(text),
|
|
202
|
+
input = process.stdin,
|
|
203
|
+
output = process.stdout,
|
|
204
|
+
} = {}) {
|
|
205
|
+
const json = flags.json === true || flags.json === 'true';
|
|
206
|
+
const show = (value, text) => print(json ? JSON.stringify(value, null, 2) : text);
|
|
207
|
+
|
|
208
|
+
switch (subcommand) {
|
|
209
|
+
case 'status': {
|
|
210
|
+
const value = controlStatus({ directory, env });
|
|
211
|
+
return show(value, describeStatus(value));
|
|
212
|
+
}
|
|
213
|
+
case 'on': {
|
|
214
|
+
const personas = hermesConnections(env);
|
|
215
|
+
if (personas.length === 0) throw new Error('No Hermes persona is linked on this computer yet. Link one first (oomi connect), then run: oomi control on');
|
|
216
|
+
// Refuse before asking, so the person isn't asked to confirm something that can't be done.
|
|
217
|
+
for (const persona of personas) {
|
|
218
|
+
if (readAllowlist(fs.readFileSync(persona.config, 'utf8')).form === 'unknown') throw new Error(`Hermes's command_allowlist in ${persona.config} isn't a plain list, so oomi left it alone.`);
|
|
219
|
+
}
|
|
220
|
+
const names = personas.map((persona) => persona.connection).join(', ');
|
|
221
|
+
const confirmation = await confirm({ resolution: resolveHelper(), reason: `Let ${names} click, type and press keys on this computer when you ask from oomi?`, env, input, output });
|
|
222
|
+
const earlier = readControl(directory);
|
|
223
|
+
const sameConfig = (persona) => (entry) => entry.config.toLowerCase() === persona.config.toLowerCase();
|
|
224
|
+
// Personas that were linked before keep their record, so off still takes back what on gave them.
|
|
225
|
+
const runtimes = earlier.runtimes.filter((entry) => !personas.some((persona) => sameConfig(persona)(entry)));
|
|
226
|
+
const { runtimes: _earlierRuntimes, ...state } = earlier;
|
|
227
|
+
for (const persona of personas) {
|
|
228
|
+
const before = earlier.runtimes.find(sameConfig(persona))?.added || [];
|
|
229
|
+
const present = new Set(readAllowlist(fs.readFileSync(persona.config, 'utf8')).items);
|
|
230
|
+
const adding = hermesDesktopGrants().filter((key) => !present.has(key));
|
|
231
|
+
runtimes.push({ runtime: 'hermes', connection: persona.connection, config: persona.config, added: [...new Set([...before, ...adding])] });
|
|
232
|
+
// Written down before the config changes: if this or a later persona's write fails, off can still take it back.
|
|
233
|
+
writePrivateJson(controlPath(directory), { ...state, updatedAt: new Date().toISOString(), runtimes });
|
|
234
|
+
grantHermesDesktop(persona.config);
|
|
235
|
+
}
|
|
236
|
+
writePrivateJson(controlPath(directory), { version: 1, enabled: true, confirmedAt: confirmation.at, confirmedWith: confirmation.method, updatedAt: new Date().toISOString(), runtimes });
|
|
237
|
+
const value = controlStatus({ directory, env });
|
|
238
|
+
return show({ ok: true, ...value }, `Computer control is on.\n${describeStatus(value)}`);
|
|
239
|
+
}
|
|
240
|
+
case 'off': {
|
|
241
|
+
const control = readControl(directory);
|
|
242
|
+
for (const entry of control.runtimes) revokeHermesDesktop(entry.config, entry.added);
|
|
243
|
+
writePrivateJson(controlPath(directory), { version: 1, enabled: false, confirmedAt: null, confirmedWith: null, updatedAt: new Date().toISOString(), runtimes: [] });
|
|
244
|
+
const value = controlStatus({ directory, env });
|
|
245
|
+
return show({ ok: true, ...value }, `Computer control is off.\n${describeStatus(value)}`);
|
|
246
|
+
}
|
|
247
|
+
case 'help':
|
|
248
|
+
return print(USAGE);
|
|
249
|
+
default:
|
|
250
|
+
throw new Error(`Unknown control command: ${subcommand}\n${USAGE}`);
|
|
251
|
+
}
|
|
252
|
+
}
|
package/lib/hermesAcp.js
CHANGED
|
@@ -14,6 +14,17 @@ import { spawn } from 'node:child_process';
|
|
|
14
14
|
const PROTOCOL_VERSION = 1;
|
|
15
15
|
const START_TIMEOUT_MS = 20000;
|
|
16
16
|
const CONTROL_TIMEOUT_MS = 30000;
|
|
17
|
+
// Hermes 0.23 on Windows leaves the first session request of a process unanswered until another
|
|
18
|
+
// `session/new` arrives a few seconds later. Measured on 2026-11-15: no answer in 3 minutes
|
|
19
|
+
// alone; answered in 3.8 s with a second one sent 3 s after it; two sent at the same moment both
|
|
20
|
+
// waited; a different request didn't release it. Every later session answers in 1 to 2 s. Timing
|
|
21
|
+
// the first one out at 30 s failed the first turn after every bridge start. So an unanswered first
|
|
22
|
+
// request is followed by `session/new` nudges, and the sessions those make are kept to spare for
|
|
23
|
+
// the next conversations that need a new one.
|
|
24
|
+
const FIRST_SESSION_TIMEOUT_MS = 90000;
|
|
25
|
+
const FIRST_SESSION_NUDGES_MS = [3000, 6000, 12000];
|
|
26
|
+
/** Tests shorten these. */
|
|
27
|
+
export const acpTimeouts = { control: CONTROL_TIMEOUT_MS, firstSession: FIRST_SESSION_TIMEOUT_MS, nudges: FIRST_SESSION_NUDGES_MS };
|
|
17
28
|
const UNAVAILABLE_BACKOFF_MS = 10 * 60 * 1000;
|
|
18
29
|
const TEXT_INTERVAL_MS = 80;
|
|
19
30
|
const MAX_REPLY_CHARS = 4 * 1024 * 1024;
|
|
@@ -76,10 +87,17 @@ class HermesAcpClient {
|
|
|
76
87
|
this.turns = new Map();
|
|
77
88
|
this.loaded = new Set();
|
|
78
89
|
this.replayed = new Map();
|
|
90
|
+
// True once this process has answered a session request: its first one is behind it.
|
|
91
|
+
this.warmed = false;
|
|
92
|
+
this.firstSession = null;
|
|
93
|
+
// Sessions opened ahead of need ({ sessionId, models }), for conversations that need a new one.
|
|
94
|
+
this.spares = [];
|
|
79
95
|
// The model each ACP session is on and what Hermes can switch to (session/new and
|
|
80
96
|
// session/load answers), for `/model` in Talk and to put back a conversation an older bridge
|
|
81
97
|
// left on a call's model (restoreChatModel).
|
|
82
98
|
this.sessionModels = new Map();
|
|
99
|
+
// Sessions with a `/steer` request not yet answered (see steer()).
|
|
100
|
+
this.steering = new Map();
|
|
83
101
|
this.availableModels = [];
|
|
84
102
|
this.defaultModel = '';
|
|
85
103
|
this.closed = false;
|
|
@@ -175,7 +193,7 @@ class HermesAcpClient {
|
|
|
175
193
|
if (initialized?.protocolVersion !== PROTOCOL_VERSION) throw unavailable();
|
|
176
194
|
}
|
|
177
195
|
|
|
178
|
-
request(method, params, timeoutMs =
|
|
196
|
+
request(method, params, timeoutMs = acpTimeouts.control) {
|
|
179
197
|
if (this.closed || !this.child) return Promise.reject(exited());
|
|
180
198
|
const id = ++this.nextId;
|
|
181
199
|
return new Promise((resolve, reject) => {
|
|
@@ -223,7 +241,13 @@ class HermesAcpClient {
|
|
|
223
241
|
if (this.replayed.has(sessionId)) this.replayed.set(sessionId, this.replayed.get(sessionId) + 1);
|
|
224
242
|
const turn = this.turns.get(sessionId);
|
|
225
243
|
const update = params.update;
|
|
226
|
-
|
|
244
|
+
// Hermes confirms a steer with a line of its own ("Steer queued for the active turn: ..."),
|
|
245
|
+
// sent without a message id before it answers the steer. It isn't the persona's reply.
|
|
246
|
+
if (this.steering.get(sessionId) && update?.sessionUpdate === 'agent_message_chunk' && !update.messageId) return;
|
|
247
|
+
if (!turn) return;
|
|
248
|
+
if (update?.sessionUpdate === 'tool_call') return void turn.onTool?.(update);
|
|
249
|
+
if (update?.sessionUpdate === 'tool_call_update') return void turn.onToolUpdate?.(update);
|
|
250
|
+
if (update?.sessionUpdate !== 'agent_message_chunk' || update.content?.type !== 'text') return;
|
|
227
251
|
turn.onChunk(String(update.content.text || ''), update.messageId);
|
|
228
252
|
}
|
|
229
253
|
|
|
@@ -248,7 +272,7 @@ class HermesAcpClient {
|
|
|
248
272
|
// counts as found only when its history is replayed.
|
|
249
273
|
this.replayed.set(sessionId, 0);
|
|
250
274
|
try {
|
|
251
|
-
const loaded = await this.
|
|
275
|
+
const loaded = await this.sessionRequest('session/load', { sessionId, cwd, mcpServers: [] });
|
|
252
276
|
this.noteModels(sessionId, loaded?.models);
|
|
253
277
|
if (this.replayed.get(sessionId) > 0) {
|
|
254
278
|
await this.prepare(sessionId);
|
|
@@ -259,25 +283,90 @@ class HermesAcpClient {
|
|
|
259
283
|
} finally { this.replayed.delete(sessionId); }
|
|
260
284
|
}
|
|
261
285
|
if (!create) return null;
|
|
262
|
-
const created = await this.
|
|
286
|
+
const created = this.spares.shift() || await this.sessionRequest('session/new', { cwd, mcpServers: [] });
|
|
263
287
|
if (typeof created?.sessionId !== 'string' || !created.sessionId) throw unavailable();
|
|
264
288
|
this.noteModels(created.sessionId, created.models, { created: true });
|
|
265
289
|
await this.prepare(created.sessionId);
|
|
266
290
|
return { sessionId: created.sessionId, created: true };
|
|
267
291
|
}
|
|
268
292
|
|
|
293
|
+
/**
|
|
294
|
+
* `session/new` or `session/load`. The first one a process answers may need nudging (see the
|
|
295
|
+
* note at the top); the others wait for it, so only one request is ever nudged.
|
|
296
|
+
*/
|
|
297
|
+
async sessionRequest(method, params) {
|
|
298
|
+
if (this.firstSession) await this.firstSession.catch(() => {});
|
|
299
|
+
if (this.warmed) return this.request(method, params);
|
|
300
|
+
let answered = false;
|
|
301
|
+
const first = this.request(method, params, acpTimeouts.firstSession);
|
|
302
|
+
this.firstSession = first;
|
|
303
|
+
const nudge = async () => {
|
|
304
|
+
for (const wait of acpTimeouts.nudges) {
|
|
305
|
+
await new Promise((resolve) => { setTimeout(resolve, wait).unref?.(); });
|
|
306
|
+
if (answered || this.closed) return;
|
|
307
|
+
this.request('session/new', { cwd: this.config.cwd, mcpServers: [] }, acpTimeouts.firstSession)
|
|
308
|
+
.then((spare) => { if (typeof spare?.sessionId === 'string' && spare.sessionId) this.spares.push(spare); })
|
|
309
|
+
.catch(() => {});
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
nudge();
|
|
313
|
+
try {
|
|
314
|
+
const result = await first;
|
|
315
|
+
this.warmed = true;
|
|
316
|
+
return result;
|
|
317
|
+
} finally {
|
|
318
|
+
answered = true;
|
|
319
|
+
this.firstSession = null;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Hands more words to the turn in progress in this session, without stopping it: Hermes's
|
|
325
|
+
* `/steer`, which gives them to the model at its next step, to carry on, change course or stop
|
|
326
|
+
* as it judges. Measured on 2026-11-15: sent 7 s into a turn, answered at once, and the turn
|
|
327
|
+
* finished on the new words. False when no turn is running here, so nothing was handed over.
|
|
328
|
+
*/
|
|
329
|
+
async steer(sessionId, text) {
|
|
330
|
+
const words = String(text || '').replace(/\s+/g, ' ').trim();
|
|
331
|
+
if (!words || this.closed || !this.turns.has(sessionId)) return false;
|
|
332
|
+
this.steering.set(sessionId, (this.steering.get(sessionId) || 0) + 1);
|
|
333
|
+
try {
|
|
334
|
+
await this.request('session/prompt', { sessionId, prompt: [{ type: 'text', text: `/steer ${words}` }] });
|
|
335
|
+
return true;
|
|
336
|
+
} catch {
|
|
337
|
+
return false;
|
|
338
|
+
} finally {
|
|
339
|
+
const left = (this.steering.get(sessionId) || 1) - 1;
|
|
340
|
+
if (left > 0) this.steering.set(sessionId, left); else this.steering.delete(sessionId);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Opens a session ahead of need, if this process has none to spare. */
|
|
345
|
+
async makeSpare() {
|
|
346
|
+
if (this.spares.length) return;
|
|
347
|
+
const spare = await this.sessionRequest('session/new', { cwd: this.config.cwd, mcpServers: [] });
|
|
348
|
+
if (typeof spare?.sessionId === 'string' && spare.sessionId) this.spares.push(spare);
|
|
349
|
+
}
|
|
350
|
+
|
|
269
351
|
async prepare(sessionId) {
|
|
270
352
|
// Without this mode Hermes asks before every file edit, which Oomi would deny.
|
|
271
353
|
await this.request('session/set_mode', { sessionId, modeId: EDIT_MODE }).catch(() => {});
|
|
272
354
|
this.loaded.add(sessionId);
|
|
273
355
|
}
|
|
274
356
|
|
|
275
|
-
|
|
357
|
+
/**
|
|
358
|
+
* One turn. `onWorking` is told each time the persona starts a tool, after what it has said so
|
|
359
|
+
* far is sent on. `timing` is filled with where the time went, in ms from the turn's start:
|
|
360
|
+
* firstTextMs, lastTextMs, doneMs and tools [{kind, startMs, endMs}]. No words, no commands.
|
|
361
|
+
*/
|
|
362
|
+
prompt(sessionId, prompt, { signal, timeoutMs = 180000, onText, onWorking, timing = {} } = {}) {
|
|
276
363
|
if (this.turns.has(sessionId)) return Promise.reject(new HermesAcpError('hermes_session_busy', 'Hermes is still answering in this conversation.', { notStarted: true }));
|
|
277
364
|
return new Promise((resolve, reject) => {
|
|
278
365
|
let text = '';
|
|
279
366
|
let sent = '';
|
|
280
367
|
let messageId;
|
|
368
|
+
const began = Date.now();
|
|
369
|
+
const tools = [];
|
|
281
370
|
let textTimer = null;
|
|
282
371
|
let settled = false;
|
|
283
372
|
const flush = () => {
|
|
@@ -304,12 +393,31 @@ class HermesAcpClient {
|
|
|
304
393
|
// Words before and after a tool call are separate messages; keep them apart.
|
|
305
394
|
if (id && messageId && id !== messageId && text && !/\s$/.test(text)) text += '\n\n';
|
|
306
395
|
if (id) messageId = id;
|
|
396
|
+
// One blank line between what it says before and after its work, however Hermes spaces them.
|
|
397
|
+
if (/\n\n$/.test(text)) chunk = chunk.replace(/^\n+/, '');
|
|
398
|
+
if (!chunk) return;
|
|
307
399
|
if (text.length + chunk.length > MAX_REPLY_CHARS) return cancel(new HermesAcpError('too_long', 'Agent output exceeded 4 MiB.'));
|
|
308
400
|
text += chunk;
|
|
401
|
+
timing.firstTextMs ??= Date.now() - began;
|
|
402
|
+
timing.lastTextMs = Date.now() - began;
|
|
309
403
|
// Send the first words right away, then at most every TEXT_INTERVAL_MS.
|
|
310
404
|
if (!sent) flush();
|
|
311
405
|
else textTimer ??= setTimeout(flush, TEXT_INTERVAL_MS);
|
|
312
406
|
},
|
|
407
|
+
// The persona has gone to work. What it said first ("I'll open it now.") ends here as a line
|
|
408
|
+
// of its own and is sent on at once, so a call can speak it while the tool runs.
|
|
409
|
+
onTool: (update) => {
|
|
410
|
+
if (settled) return;
|
|
411
|
+
tools.push({ id: update.toolCallId, kind: String(update.kind || 'other').slice(0, 24), startMs: Date.now() - began });
|
|
412
|
+
if (text && !/\n\s*$/.test(text)) text += '\n\n';
|
|
413
|
+
clearTimeout(textTimer);
|
|
414
|
+
flush();
|
|
415
|
+
onWorking?.();
|
|
416
|
+
},
|
|
417
|
+
onToolUpdate: (update) => {
|
|
418
|
+
const tool = tools.find((entry) => entry.id === update.toolCallId && entry.endMs === undefined);
|
|
419
|
+
if (tool && ['completed', 'failed'].includes(update.status)) tool.endMs = Date.now() - began;
|
|
420
|
+
},
|
|
313
421
|
fail: (error) => finish(reject, error),
|
|
314
422
|
});
|
|
315
423
|
if (signal?.aborted) return abort();
|
|
@@ -325,6 +433,8 @@ class HermesAcpClient {
|
|
|
325
433
|
if (!reply) return finish(reject, new HermesAcpError('empty_reply', 'Agent did not return a successful final reply.'));
|
|
326
434
|
clearTimeout(textTimer);
|
|
327
435
|
flush();
|
|
436
|
+
timing.doneMs = Date.now() - began;
|
|
437
|
+
if (tools.length) timing.tools = tools.slice(0, 40).map(({ kind, startMs, endMs }) => ({ kind, startMs, ...(endMs === undefined ? {} : { endMs }) }));
|
|
328
438
|
finish(resolve, reply);
|
|
329
439
|
}, (err) => finish(reject, err));
|
|
330
440
|
});
|
|
@@ -393,34 +503,42 @@ function promptBlocks(request, seed) {
|
|
|
393
503
|
|
|
394
504
|
/**
|
|
395
505
|
* Starts Hermes ahead of the first message and reopens recent conversations, so a call's first
|
|
396
|
-
* turn doesn't wait for Hermes to start (about 3.5 s on the maintainer's Mac).
|
|
506
|
+
* turn doesn't wait for Hermes to start (about 3.5 s on the maintainer's Mac). With nothing to
|
|
507
|
+
* reopen, it opens one session to spare, so the process's first session is opened here and not
|
|
508
|
+
* by the person's first message; the next new conversation uses that session.
|
|
397
509
|
*/
|
|
398
510
|
export async function warmHermesAcp(config, sessionIds = []) {
|
|
399
511
|
const client = hermesAcpClient(config);
|
|
400
512
|
await client.start();
|
|
401
513
|
for (const sessionId of sessionIds) await client.openSession(sessionId, { create: false }).catch(() => null);
|
|
514
|
+
if (!client.warmed) await client.makeSpare();
|
|
402
515
|
}
|
|
403
516
|
|
|
404
517
|
/** One Hermes turn over ACP. Returns the reply and the ACP session that holds the conversation. */
|
|
405
|
-
export async function runHermesAcpTurn(config, request, { signal, timeoutMs = 180000, onText } = {}) {
|
|
518
|
+
export async function runHermesAcpTurn(config, request, { signal, timeoutMs = 180000, onText, onSession, onWorking } = {}) {
|
|
519
|
+
const timing = {};
|
|
406
520
|
const client = hermesAcpClient(config);
|
|
407
521
|
await client.start();
|
|
522
|
+
// A warm-up still opening its first session finishes first; this turn then takes a spare one.
|
|
523
|
+
if (client.firstSession) await client.firstSession.catch(() => {});
|
|
408
524
|
const continuing = request.runtimeTransport === 'acp' ? request.runtimeSessionId : '';
|
|
409
525
|
let { sessionId, created } = await client.openSession(continuing);
|
|
410
526
|
const seed = () => continuityPreamble(request.history);
|
|
411
527
|
let chatModel = await restoreChatModel(client, sessionId, request);
|
|
412
528
|
let text;
|
|
529
|
+
onSession?.(sessionId);
|
|
413
530
|
try {
|
|
414
531
|
// A session `/model` opened for a conversation with history hasn't heard it yet.
|
|
415
|
-
text = await client.prompt(sessionId, promptBlocks(request, created || request.seedPending ? seed() : ''), { signal, timeoutMs, onText });
|
|
532
|
+
text = await client.prompt(sessionId, promptBlocks(request, created || request.seedPending ? seed() : ''), { signal, timeoutMs, onText, onWorking, timing });
|
|
416
533
|
} catch (err) {
|
|
417
534
|
if (err.code !== 'hermes_session_unknown' || created) throw err;
|
|
418
535
|
({ sessionId } = await client.openSession(''));
|
|
536
|
+
onSession?.(sessionId);
|
|
419
537
|
// A fresh session starts on the persona's own model.
|
|
420
538
|
chatModel = null;
|
|
421
|
-
text = await client.prompt(sessionId, promptBlocks(request, seed()), { signal, timeoutMs, onText });
|
|
539
|
+
text = await client.prompt(sessionId, promptBlocks(request, seed()), { signal, timeoutMs, onText, onWorking, timing });
|
|
422
540
|
}
|
|
423
|
-
return { text, sessionId, transport: 'acp', chatModel };
|
|
541
|
+
return { text, sessionId, transport: 'acp', chatModel, timing };
|
|
424
542
|
}
|
|
425
543
|
|
|
426
544
|
/**
|
|
@@ -439,6 +557,12 @@ export async function hermesAcpModels(config, sessionId, { create = false } = {}
|
|
|
439
557
|
return { session, current, available: client.availableModels };
|
|
440
558
|
}
|
|
441
559
|
|
|
560
|
+
/** Hands `text` to the Hermes turn running in `sessionId` (HermesAcpClient.steer). */
|
|
561
|
+
export async function steerHermesAcp(config, sessionId, text) {
|
|
562
|
+
const client = clients.get(clientKey(config));
|
|
563
|
+
return Boolean(client && !client.closed && sessionId && await client.steer(sessionId, text));
|
|
564
|
+
}
|
|
565
|
+
|
|
442
566
|
/** Switches a conversation's session (opened or made here) to `modelId`, for this conversation only. */
|
|
443
567
|
export async function setHermesAcpModel(config, sessionId, modelId) {
|
|
444
568
|
const client = hermesAcpClient(config);
|