@hmharness/cli 0.23.20 → 0.23.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ import { type ChatMessage } from '@hmharness/kernel';
2
+ import { type RunnerEvents } from '@hmharness/agent';
3
+ /** close every window NOT in the protected snapshot whose tabs are ALL
4
+ * blank (the host's per-connection workspace windows). Protected-set
5
+ * windows — everything that existed when our connection initialized —
6
+ * are never touched. Returns how many closed; never throws. */
7
+ export declare function recycleBlankWindows(port: number, protectedWindows: Set<number>): Promise<number>;
8
+ interface AcpSession {
9
+ cwd: string;
10
+ /** hmh rollout id once the first prompt ran (resume appends) */
11
+ hmhId?: string;
12
+ /** full transcript of the last completed turn (resume input) */
13
+ messages?: ChatMessage[];
14
+ abort?: AbortController;
15
+ }
16
+ export interface AcpIo {
17
+ /** write one ndjson frame to the client */
18
+ send(frame: unknown): void;
19
+ /** agent→client request with a matched response */
20
+ request(method: string, params: unknown): Promise<unknown>;
21
+ }
22
+ export interface AcpRunTaskArgs {
23
+ prompt: string;
24
+ cwd: string;
25
+ sessionId?: string;
26
+ resumeMessages?: ChatMessage[];
27
+ signal: AbortSignal;
28
+ events: RunnerEvents;
29
+ approvalAsk?: (toolName: string, args: Record<string, unknown>) => Promise<boolean>;
30
+ }
31
+ export type AcpRunTask = (args: AcpRunTaskArgs) => Promise<{
32
+ text: string;
33
+ turns: number;
34
+ toolUses: number;
35
+ sessionId: string;
36
+ messages: ChatMessage[];
37
+ }>;
38
+ export interface CreateAcpServerOptions {
39
+ io: AcpIo;
40
+ /** injectable for tests; the default wires runAgentTask */
41
+ runTask?: AcpRunTask;
42
+ home?: string;
43
+ /** connection lifecycle hooks (host-window recycling etc.); never throw */
44
+ onInitialized?: () => Promise<void>;
45
+ onTurnSettled?: () => Promise<void>;
46
+ /** create a persistent hmh rollout id for a NEW session (default: real
47
+ * Session.create; tests inject a fixed id). The ACP session id IS the
48
+ * hmh rollout id, so session/load reconnects straight to the rollout. */
49
+ createRollout?: (cwd: string) => Promise<string>;
50
+ /** load a prior rollout's transcript for session/load (default: real
51
+ * loadTranscript; tests may stub) */
52
+ loadRollout?: (sessionId: string) => Promise<ChatMessage[] | undefined>;
53
+ }
54
+ /** Pure protocol core — every frame in, frames/requests out. Testable
55
+ * without stdio or a model. */
56
+ export declare function createAcpServer(opts: CreateAcpServerOptions): {
57
+ handle(msg: unknown): Promise<void>;
58
+ sessions: Map<string, AcpSession>;
59
+ };
60
+ /** Wire the protocol core to real stdio. Exits when stdin closes. */
61
+ export declare function serveAcp(): Promise<void>;
62
+ export {};
@@ -0,0 +1,549 @@
1
+ /**
2
+ * @hmharness/cli - acp-serve (Agent Client Protocol server mode)
3
+ *
4
+ * Makes hmharness a FIRST-CLASS agent inside ACP hosts — BrowserOS's
5
+ * assistant panel (Custom ACP agent), Zed, and every client that speaks
6
+ * the 2026 ACP interop baseline. The HOST owns the chat UI; hmharness
7
+ * stays the brain: its provider config, its tool registry (incl. the
8
+ * browser_* family that drives BrowserOS itself), its sessions.
9
+ *
10
+ * Protocol: ndjson JSON-RPC 2.0 over stdio (initialize / session/new /
11
+ * session/prompt / session/cancel + session/update notifications +
12
+ * session/request_permission agent→client round-trip), wire shapes per
13
+ * the official @zed-industries/agent-client-protocol reference agent.
14
+ * stdout belongs to the protocol — every stray print goes to stderr.
15
+ *
16
+ * Security model (mirrors mcp-server mode):
17
+ * - the FULL native tool registry is available (this is hmharness's
18
+ * own agent, not a tool projection);
19
+ * - gated tools route their approval through request_permission —
20
+ * the host's Allow/Reject buttons ARE the approval card;
21
+ * - cwd comes from the host's session/new (validated, fallback to
22
+ * process cwd); home is HMH_HOME as always.
23
+ */
24
+ import readline from 'node:readline';
25
+ import { existsSync } from 'node:fs';
26
+ import { isAbsolute, join, resolve } from 'node:path';
27
+ import { homeDir, loadConfig } from '@hmharness/kernel';
28
+ import { buildRegistry, runAgentTask } from '@hmharness/agent';
29
+ /* ------------------------------------------------------------------ *
30
+ * Host-browser window recycling (BrowserOS "workspace window" answer)
31
+ *
32
+ * BrowserOS assigns EVERY new ACP connection its own browsing window
33
+ * (a workspace with a fresh new-tab). Since the host re-spawns the agent
34
+ * per message, windows accumulate one per message — protocol-level
35
+ * loadSession keeps the CONVERSATION continuous but cannot stop the
36
+ * window-per-connection behavior. So we recycle: snapshot the host's
37
+ * windows when the connection initializes, and after each turn close the
38
+ * windows that (a) appeared since and (b) contain ONLY blank pages
39
+ * (new-tab / about:blank). A window with real content is never touched —
40
+ * that makes the sweep safe even if the user opened something meanwhile.
41
+ * Uses BrowserOS's extended CDP Browser domain over the attach port.
42
+ */
43
+ async function hostBrowserCall(port, method, params = {}, timeoutMs = 5_000) {
44
+ const ver = (await (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1_500) })).json());
45
+ return new Promise((resolve, reject) => {
46
+ let settled = false;
47
+ const ws = new WebSocket(ver.webSocketDebuggerUrl);
48
+ const timer = setTimeout(() => { if (!settled) {
49
+ settled = true;
50
+ try {
51
+ ws.close();
52
+ }
53
+ catch { /* gone */ }
54
+ reject(new Error('hostBrowserCall timeout'));
55
+ } }, timeoutMs);
56
+ ws.addEventListener('open', () => ws.send(JSON.stringify({ id: 1, method, params })), { once: true });
57
+ ws.addEventListener('message', (ev) => {
58
+ if (settled)
59
+ return;
60
+ const m = JSON.parse(typeof ev.data === 'string' ? ev.data : Buffer.from(ev.data).toString());
61
+ if (m.id !== 1)
62
+ return;
63
+ settled = true;
64
+ clearTimeout(timer);
65
+ try {
66
+ ws.close();
67
+ }
68
+ catch { /* gone */ }
69
+ if (m.error)
70
+ reject(new Error(m.error.message ?? 'host Browser domain error'));
71
+ else
72
+ resolve(m.result);
73
+ });
74
+ ws.addEventListener('error', () => { if (!settled) {
75
+ settled = true;
76
+ clearTimeout(timer);
77
+ reject(new Error('host CDP socket error'));
78
+ } }, { once: true });
79
+ });
80
+ }
81
+ async function listHostWindows(port) {
82
+ const r = await hostBrowserCall(port, 'Browser.getWindows');
83
+ return new Set((r.windows ?? []).map((w) => Number(w.windowId)).filter((n) => Number.isInteger(n)));
84
+ }
85
+ async function windowIsBlank(port, windowId) {
86
+ const tabs = await hostBrowserCall(port, 'Browser.getTabs', { windowId });
87
+ const urls = (tabs.tabs ?? []).map((t) => t.url ?? '');
88
+ return urls.length > 0 && urls.every((u) => u === 'chrome://newtab/' || u === 'about:blank' || u === '');
89
+ }
90
+ /** the windows we must NEVER touch: those holding real content */
91
+ async function listContentWindows(port) {
92
+ const all = await listHostWindows(port);
93
+ const content = new Set();
94
+ for (const w of all) {
95
+ try {
96
+ if (!(await windowIsBlank(port, w)))
97
+ content.add(w);
98
+ }
99
+ catch { /* unreadable window = treat as content (safe side) */ }
100
+ }
101
+ return content;
102
+ }
103
+ /** close every window NOT in the protected snapshot whose tabs are ALL
104
+ * blank (the host's per-connection workspace windows). Protected-set
105
+ * windows — everything that existed when our connection initialized —
106
+ * are never touched. Returns how many closed; never throws. */
107
+ export async function recycleBlankWindows(port, protectedWindows) {
108
+ try {
109
+ const current = await listHostWindows(port);
110
+ let closed = 0;
111
+ for (const windowId of current) {
112
+ if (protectedWindows.has(windowId))
113
+ continue;
114
+ try {
115
+ if (await windowIsBlank(port, windowId)) {
116
+ await hostBrowserCall(port, 'Browser.closeWindow', { windowId });
117
+ closed++;
118
+ }
119
+ }
120
+ catch { /* one window failing must not stop the sweep */ }
121
+ }
122
+ return closed;
123
+ }
124
+ catch {
125
+ return 0; // host unreachable / domain missing: recycle is best-effort
126
+ }
127
+ }
128
+ /** read-ish tools render as 'read', editors as 'edit', the rest 'execute' */
129
+ function kindFor(name) {
130
+ if (/^(read_file|list_dir|web_fetch|web_search|see_image|lsp_|cognitive_query|browser_snapshot|browser_read|browser_tabs|desktop_screenshot)/.test(name))
131
+ return 'read';
132
+ if (/^(edit_file|write_file|browser_type)/.test(name))
133
+ return 'edit';
134
+ return 'execute';
135
+ }
136
+ function titleFor(name, args) {
137
+ const first = ['file', 'path', 'url', 'command', 'host', 'query', 'ref'].find((k) => typeof args[k] === 'string' && args[k]);
138
+ return first ? `${name} ${String(args[first]).slice(0, 80)}` : name;
139
+ }
140
+ /** Pure protocol core — every frame in, frames/requests out. Testable
141
+ * without stdio or a model. */
142
+ export function createAcpServer(opts) {
143
+ const io = opts.io;
144
+ const sessions = new Map();
145
+ const home = () => opts.home ?? homeDir();
146
+ // one registry for the server's lifetime (MCP handshakes are not free);
147
+ // rebuilt only if a build fails outright
148
+ let registryPromise = null;
149
+ const registry = () => (registryPromise ??= buildRegistry({ mcp: true, announce: false }));
150
+ const runTask = opts.runTask ?? (async (a) => {
151
+ const cfg = await loadConfig();
152
+ const { reg } = await registry();
153
+ const r = await runAgentTask({
154
+ task: a.prompt,
155
+ registry: reg,
156
+ cfg,
157
+ ctx: { cwd: a.cwd, home: home() },
158
+ resumeMessages: a.resumeMessages,
159
+ sessionId: a.sessionId,
160
+ events: a.events,
161
+ signal: a.signal,
162
+ ...(a.approvalAsk ? { approvalAsk: a.approvalAsk } : {}),
163
+ });
164
+ return { text: r.text, turns: r.turns, toolUses: r.toolUses, sessionId: r.sessionId, messages: r.messages };
165
+ });
166
+ const createRollout = opts.createRollout ?? (async (cwd) => {
167
+ const { Session } = await import('@hmharness/kernel');
168
+ const cfg = await loadConfig();
169
+ return Session.create(home(), cwd, cfg.provider.model).id;
170
+ });
171
+ const loadRollout = opts.loadRollout ?? (async (sessionId) => {
172
+ try {
173
+ const { Session, loadTranscript } = await import('@hmharness/kernel');
174
+ const s = await Session.resume(home(), sessionId);
175
+ return s ? (await loadTranscript(s.file))?.messages : undefined;
176
+ }
177
+ catch {
178
+ return undefined;
179
+ }
180
+ });
181
+ const update = (sessionId, upd) => {
182
+ io.send({ jsonrpc: '2.0', method: 'session/update', params: { sessionId, update: upd } });
183
+ };
184
+ const err = (id, code, message) => {
185
+ if (id === null || id === undefined)
186
+ return;
187
+ io.send({ jsonrpc: '2.0', id, error: { code, message } });
188
+ };
189
+ async function handle(msg) {
190
+ const m = msg;
191
+ if (!m || typeof m.method !== 'string')
192
+ return; // not a request/notification — ignore
193
+ const isRequest = m.id !== undefined && m.id !== null;
194
+ const ok = (result) => {
195
+ if (isRequest)
196
+ io.send({ jsonrpc: '2.0', id: m.id, result });
197
+ };
198
+ switch (m.method) {
199
+ case 'initialize': {
200
+ // echo the client's version when present: the core surface we
201
+ // implement (initialize/new/load/prompt/cancel/update/permission) is
202
+ // stable across the 0.4 interop baseline and later additions are
203
+ // optional; a hard version mismatch would just refuse to connect.
204
+ // loadSession + sessionCapabilities: the host treats agents that
205
+ // declare session-lifecycle capabilities (close/delete/fork/list/
206
+ // resume — observed on the built-in claude-agent-acp) as long-lived
207
+ // manageable sessions and REUSES the connection; without them it
208
+ // spawns a fresh agent (and a fresh workspace WINDOW) per message —
209
+ // the exact "a new browser window on every message" bug.
210
+ ok({
211
+ protocolVersion: m.params?.protocolVersion ?? '0',
212
+ agentCapabilities: {
213
+ loadSession: true,
214
+ sessionCapabilities: {
215
+ additionalDirectories: {},
216
+ close: {},
217
+ delete: {},
218
+ fork: {},
219
+ list: {},
220
+ resume: {},
221
+ },
222
+ // the host hands every session a browser MCP over http (with an
223
+ // internal lease header) — declaring we speak http MCP may be
224
+ // what keeps it from provisioning a workspace WINDOW instead
225
+ mcpCapabilities: { http: true, sse: false },
226
+ },
227
+ authMethods: [],
228
+ });
229
+ await opts.onInitialized?.().catch(() => undefined);
230
+ return;
231
+ }
232
+ case 'session/close':
233
+ case 'session/delete': {
234
+ const sid = m.params?.sessionId;
235
+ if (sid)
236
+ sessions.delete(sid);
237
+ ok({});
238
+ return;
239
+ }
240
+ case 'session/list': {
241
+ ok({ sessions: [...sessions.keys()].map((id) => ({ sessionId: id, ...(sessions.get(id).hmhId ? { title: sessions.get(id).hmhId } : {}) })) });
242
+ return;
243
+ }
244
+ case 'authenticate': {
245
+ ok({});
246
+ return;
247
+ }
248
+ case 'session/new': {
249
+ const rawCwd = typeof m.params?.cwd === 'string' ? m.params.cwd : '';
250
+ const cwd = isAbsolute(rawCwd) && existsSync(rawCwd) ? rawCwd : process.cwd();
251
+ const sessionId = await createRollout(resolve(cwd));
252
+ sessions.set(sessionId, { cwd: resolve(cwd), hmhId: sessionId });
253
+ ok({ sessionId });
254
+ return;
255
+ }
256
+ case 'session/load':
257
+ case 'session/resume': {
258
+ // `session/resume` is the acpx host's name for the same operation
259
+ // (observed on the wire) — both register the prior session and
260
+ // restore its transcript from the hmh rollout.
261
+ const sid = typeof m.params?.sessionId === 'string' ? m.params.sessionId : '';
262
+ if (!sid) {
263
+ err(m.id, -32602, `${m.method} needs sessionId`);
264
+ return;
265
+ }
266
+ if (!sessions.has(sid)) {
267
+ const rawCwd = typeof m.params?.cwd === 'string' ? m.params.cwd : '';
268
+ const cwd = isAbsolute(rawCwd) && existsSync(rawCwd) ? resolve(rawCwd) : process.cwd();
269
+ // restore the transcript from the hmh rollout; a missing/cleaned
270
+ // rollout still loads (the runner falls back to a fresh session)
271
+ sessions.set(sid, { cwd, hmhId: sid, messages: await loadRollout(sid) });
272
+ }
273
+ ok({ sessionId: sid });
274
+ return;
275
+ }
276
+ case 'session/set_mode': {
277
+ ok({});
278
+ return;
279
+ }
280
+ case 'session/cancel': {
281
+ const sid = m.params?.sessionId;
282
+ if (sid)
283
+ sessions.get(sid)?.abort?.abort();
284
+ return; // notification
285
+ }
286
+ case 'session/prompt': {
287
+ const sid = m.params?.sessionId;
288
+ const session = sid ? sessions.get(sid) : undefined;
289
+ if (!session) {
290
+ err(m.id, -32602, `unknown session ${sid ?? '(none)'}`);
291
+ return;
292
+ }
293
+ if (session.abort) {
294
+ err(m.id, -32000, 'a prompt is already running in this session');
295
+ return;
296
+ }
297
+ const blocks = Array.isArray(m.params?.prompt) ? m.params.prompt : [];
298
+ const prompt = blocks.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim();
299
+ if (!prompt) {
300
+ err(m.id, -32602, 'prompt contained no text');
301
+ return;
302
+ }
303
+ session.abort = new AbortController();
304
+ let seq = 0;
305
+ const toolIds = new Map(); // name -> stack of live ids
306
+ const cfg = await loadConfig().catch(() => undefined);
307
+ const auto = cfg?.approval === 'auto';
308
+ const events = {
309
+ onDelta(kind, chunk) {
310
+ if (!chunk)
311
+ return;
312
+ update(sid, {
313
+ sessionUpdate: kind === 'reasoning' ? 'agent_thought_chunk' : 'agent_message_chunk',
314
+ content: { type: 'text', text: chunk },
315
+ });
316
+ },
317
+ onToolCall(name, args) {
318
+ const id = `tc_${++seq}`;
319
+ const stack = toolIds.get(name) ?? [];
320
+ stack.push(id);
321
+ toolIds.set(name, stack);
322
+ update(sid, {
323
+ sessionUpdate: 'tool_call',
324
+ toolCallId: id,
325
+ title: titleFor(name, args),
326
+ kind: kindFor(name),
327
+ status: 'pending',
328
+ rawInput: args,
329
+ });
330
+ },
331
+ onToolResult(name, output, isError) {
332
+ const id = toolIds.get(name)?.pop();
333
+ if (!id)
334
+ return;
335
+ const text = output.slice(0, 2000);
336
+ update(sid, {
337
+ sessionUpdate: 'tool_call_update',
338
+ toolCallId: id,
339
+ status: isError ? 'failed' : 'completed',
340
+ content: [{ type: 'content', content: { type: 'text', text } }],
341
+ rawOutput: { text, isError },
342
+ });
343
+ },
344
+ };
345
+ const approvalAsk = auto ? undefined : async (toolName, args) => {
346
+ try {
347
+ const r = (await io.request('session/request_permission', {
348
+ sessionId: sid,
349
+ toolCall: {
350
+ toolCallId: `perm_${++seq}`,
351
+ title: titleFor(toolName, args),
352
+ kind: kindFor(toolName),
353
+ status: 'pending',
354
+ rawInput: args,
355
+ },
356
+ options: [
357
+ { kind: 'allow_once', name: 'Allow', optionId: 'allow' },
358
+ { kind: 'reject_once', name: 'Reject', optionId: 'reject' },
359
+ ],
360
+ }));
361
+ return r?.outcome?.outcome === 'selected' && r.outcome.optionId === 'allow';
362
+ }
363
+ catch {
364
+ return false; // host without permission UI / round-trip failed: deny
365
+ }
366
+ };
367
+ try {
368
+ const r = await runTask({
369
+ prompt,
370
+ cwd: session.cwd,
371
+ sessionId: session.hmhId,
372
+ resumeMessages: session.messages,
373
+ signal: session.abort.signal,
374
+ events,
375
+ approvalAsk,
376
+ });
377
+ session.hmhId = r.sessionId;
378
+ session.messages = r.messages;
379
+ ok({ stopReason: session.abort.signal.aborted ? 'cancelled' : 'end_turn' });
380
+ }
381
+ catch (e) {
382
+ // the turn still completes — with an honest error message in the
383
+ // chat rather than a bare protocol error the panel can't render
384
+ update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `\n[error] ${String(e instanceof Error ? e.message : e).slice(0, 400)}` } });
385
+ ok({ stopReason: session.abort.signal.aborted ? 'cancelled' : 'end_turn' });
386
+ }
387
+ finally {
388
+ session.abort = undefined;
389
+ // stopReason is already out; now sweep the blank workspace windows
390
+ // this connection caused (never blocks the protocol >8s)
391
+ await Promise.race([opts.onTurnSettled?.().catch(() => undefined), new Promise((r) => setTimeout(r, 8_000))]);
392
+ }
393
+ return;
394
+ }
395
+ default: {
396
+ // unknown session/* methods: answer tolerantly with {} (the host's
397
+ // extended session vocabulary evolves; a hard -32601 made it fall
398
+ // back to fresh-session-per-message behavior). The wire log records
399
+ // every such call so we can implement the ones the host actually
400
+ // uses.
401
+ if (isRequest && m.method.startsWith('session/')) {
402
+ ok({});
403
+ return;
404
+ }
405
+ if (isRequest)
406
+ err(m.id, -32601, `method not found: ${m.method}`);
407
+ }
408
+ }
409
+ }
410
+ return { handle, sessions };
411
+ }
412
+ /** Wire the protocol core to real stdio. Exits when stdin closes. */
413
+ export async function serveAcp() {
414
+ // stdout is the protocol channel: silence any library prints.
415
+ const realLog = console.log;
416
+ console.log = (...a) => console.error(...a);
417
+ void realLog;
418
+ // Host-browser attach: when spawned by BrowserOS's ACP host, its managed
419
+ // CDP port is recorded in ~/.browseros/server.json — the browser_* tools
420
+ // then drive the user's REAL tabs (their pages, their logins) instead of
421
+ // spawning a dedicated instance (which would pop a SECOND browser window
422
+ // next to the one the user is talking to us from). Standalone acp-serve
423
+ // (Zed etc.) finds no marker and keeps the dedicated-instance design.
424
+ try {
425
+ const { readFile } = await import('node:fs/promises');
426
+ const { homedir } = await import('node:os');
427
+ const { join: pjoin } = await import('node:path');
428
+ const sj = JSON.parse(await readFile(pjoin(homedir(), '.browseros', 'server.json'), 'utf8'));
429
+ if (Number.isInteger(sj.cdp_port) && sj.cdp_port > 0)
430
+ process.env.HMH_BROWSER_ATTACH = String(sj.cdp_port);
431
+ }
432
+ catch { /* not under BrowserOS — standalone mode */ }
433
+ let nextReqId = 1;
434
+ const pending = new Map();
435
+ const write = (frame) => {
436
+ process.stdout.write(JSON.stringify(frame) + '\n');
437
+ };
438
+ const io = {
439
+ send: write,
440
+ request(method, params) {
441
+ const id = nextReqId++;
442
+ return new Promise((resolve, reject) => {
443
+ pending.set(id, { resolve, reject });
444
+ write({ jsonrpc: '2.0', id, method, params });
445
+ });
446
+ },
447
+ };
448
+ // window-recycling (host browser only), SNAPSHOT-based — the safe design
449
+ // after the 2026-10-04 incident. The host opens a blank workspace window
450
+ // for every new agent connection (per-message in practice). W0 = ALL
451
+ // window ids at initialize time; sweeps close ONLY windows that (a) are
452
+ // not in W0 AND (b) currently hold nothing but blank tabs. The user's own
453
+ // windows ALWAYS predate our connection → they are in W0 → they can
454
+ // never be closed, even mid-load (the incident's failure mode). The one
455
+ // residual risk: a blank window the USER opens during our connection
456
+ // lifetime — accepted, it is empty by definition. No initialize (host
457
+ // skip) → no recycling (miss, never misfire).
458
+ const attachPort = Number(process.env.HMH_BROWSER_ATTACH ?? 0);
459
+ let w0Snapshot = null;
460
+ const recycleLog = async (msg) => {
461
+ console.error(`[acp-window] ${msg}`);
462
+ try {
463
+ const { appendFile, mkdir } = await import('node:fs/promises');
464
+ const logsDir = join(homeDir(), 'logs');
465
+ await mkdir(logsDir, { recursive: true });
466
+ await appendFile(join(logsDir, 'acp-window.log'), `${new Date().toISOString()} pid=${process.pid} ${msg}\n`, 'utf8');
467
+ }
468
+ catch { /* logging is best-effort */ }
469
+ };
470
+ const sweep = async (why) => {
471
+ if (!w0Snapshot)
472
+ return; // no initialize → no snapshot → never sweep
473
+ const closed = await recycleBlankWindows(attachPort, w0Snapshot);
474
+ await recycleLog(`${why}: closed=${closed} (W0=${w0Snapshot.size})`);
475
+ };
476
+ const recycleEnabled = process.env.HMH_BROWSER_RECYCLE !== '0' && Number.isInteger(attachPort) && attachPort > 0;
477
+ const hooks = recycleEnabled
478
+ ? {
479
+ onInitialized: async () => {
480
+ w0Snapshot = await listHostWindows(attachPort).catch(() => null);
481
+ await recycleLog(`initialize: W0 snapshot = ${w0Snapshot?.size ?? 'unavailable'} windows`);
482
+ },
483
+ onTurnSettled: async () => {
484
+ await sweep('turn-settled');
485
+ },
486
+ }
487
+ : {};
488
+ let residentTimer = null;
489
+ if (recycleEnabled) {
490
+ residentTimer = setInterval(() => { void sweep('resident').catch(() => undefined); }, 2_000);
491
+ residentTimer.unref?.();
492
+ }
493
+ const server = createAcpServer({ io, ...hooks });
494
+ const rl = readline.createInterface({ input: process.stdin });
495
+ rl.on('line', (line) => {
496
+ const text = line.trim();
497
+ if (!text)
498
+ return;
499
+ let msg;
500
+ try {
501
+ msg = JSON.parse(text);
502
+ }
503
+ catch {
504
+ console.error('[acp] unparseable frame:', text.slice(0, 120));
505
+ return;
506
+ }
507
+ // full wire log (host→agent frames): the single best forensic artifact
508
+ // for host-behavior mysteries. Truncated params keep it bounded.
509
+ void (async () => {
510
+ try {
511
+ const { appendFile, mkdir } = await import('node:fs/promises');
512
+ const logsDir = join(homeDir(), 'logs');
513
+ await mkdir(logsDir, { recursive: true });
514
+ const m = msg;
515
+ const brief = m.method
516
+ ? `${m.method} id=${String(m.id)} params=${JSON.stringify(m.params ?? {}).slice(0, 400)}`
517
+ : `response id=${String(m.id)} ${JSON.stringify(msg).slice(0, 200)}`;
518
+ await appendFile(join(logsDir, 'acp-wire.log'), `${new Date().toISOString()} ${brief}\n`, 'utf8');
519
+ }
520
+ catch { /* best-effort */ }
521
+ })();
522
+ // responses to OUR agent→client requests (permissions)
523
+ if ((msg.id !== undefined) && !('method' in msg)) {
524
+ const entry = pending.get(Number(msg.id));
525
+ if (entry) {
526
+ pending.delete(Number(msg.id));
527
+ const r = msg;
528
+ if (r.error)
529
+ entry.reject(new Error(r.error.message ?? 'request error'));
530
+ else
531
+ entry.resolve(r.result);
532
+ return;
533
+ }
534
+ }
535
+ void server.handle(msg).catch((e) => console.error('[acp] handler error:', e));
536
+ });
537
+ return new Promise((resolve) => {
538
+ rl.on('close', async () => {
539
+ for (const [, p] of pending)
540
+ p.reject(new Error('client disconnected'));
541
+ if (residentTimer)
542
+ clearInterval(residentTimer);
543
+ // last-chance sweep: the host disposes us between messages, and the
544
+ // workspace window it gave this connection would otherwise linger
545
+ await Promise.race([sweep('disconnect'), new Promise((r) => setTimeout(r, 6_000))]);
546
+ resolve();
547
+ });
548
+ });
549
+ }
package/dist/main.js CHANGED
@@ -487,7 +487,15 @@ usage:
487
487
  hmh mcp-serve run as an MCP stdio SERVER: expose harmony_* tools to
488
488
  Claude Code / Codex / any MCP host
489
489
  (host config: npx -y @hmharness/cli mcp-serve)
490
+ hmh acp-serve run as an ACP stdio AGENT: the full hmharness agent
491
+ inside ACP hosts (BrowserOS assistant panel's
492
+ "Custom ACP agent", Zed, ...)
490
493
  hmh devices|check direct tool run, no model
494
+ hmh lsp [list|trust|untrust <id>] language servers: discovery +
495
+ health + sha256 source trust (Capability OS)
496
+ hmh browser [status|trust|untrust|start|stop|open <url>]
497
+ BrowserOS AI browser: discovery + trust +
498
+ the dedicated instance browser_* tools drive
491
499
  hmh tools list all registered tools (native + MCP)
492
500
  hmh mcp show configured MCP servers and their tools
493
501
  hmh evolve [--every=N] self-evolution cycle (or resident loop)
@@ -570,6 +578,16 @@ flags:
570
578
  await serveMcp();
571
579
  return; // serveMcp exits when stdin closes
572
580
  }
581
+ if (cmd === 'acp-serve') {
582
+ // SERVER mode: be an Agent Client Protocol agent over stdio so ACP
583
+ // hosts (BrowserOS assistant panel "Custom ACP agent", Zed, ...) run
584
+ // the full hmharness agent natively in their chat UI. The host's
585
+ // Allow/Reject buttons become the approval card. stdout is the
586
+ // protocol - run this exactly as the host's agent command.
587
+ const { serveAcp } = await import("./acp-serve.js");
588
+ await serveAcp();
589
+ return; // serveAcp exits when stdin closes
590
+ }
573
591
  if (cmd === 'skills') {
574
592
  const home = homeDir();
575
593
  const flag = rest.find((a) => a.startsWith('--'));
@@ -961,6 +979,104 @@ flags:
961
979
  stdout.write('用法: hmh lsp list | trust <id> | untrust <id> — 语言服务器发现与健康/信任状态\n');
962
980
  return;
963
981
  }
982
+ if (cmd === 'browser') {
983
+ // BrowserOS management surface: discovery + trust + the agent's
984
+ // dedicated driven instance (browser_* tool family lifecycle)
985
+ await initHome();
986
+ const sub = rest[0] ?? 'status';
987
+ const { discoverBrowsers, detectRunning, listBrowserTrust, trustBrowser, untrustBrowser, startBrowser, stopBrowser, ownedInstance, BROWSEROS_INSTALL_URL } = await import('@hmharness/browser');
988
+ if (sub === 'status' || sub === 'list') {
989
+ const found = discoverBrowsers(true);
990
+ if (found.length === 0) {
991
+ stdout.write(`(本机未发现 BrowserOS——安装目录与 PATH 均无;安装: ${BROWSEROS_INSTALL_URL},或在 config.json 设 browser.executablePath)\n`);
992
+ }
993
+ const trusted = new Map((await listBrowserTrust(homeDir())).map((t) => [t.id, t]));
994
+ for (const b of found) {
995
+ const t = trusted.get(b.id);
996
+ const state = !t
997
+ ? (b.origin === 'install-local' || b.origin === 'config' ? '首次使用时自动信任(钉哈希)' : `未信任(hmh browser trust ${b.id})`)
998
+ : `${t.autoTrusted ? '自动' : '手动'}信任@${t.trustedAt.slice(0, 10)} sha:${t.sha256.slice(0, 8)}…`;
999
+ stdout.write(` ${b.healthy ? '✓' : '✗'} ${b.id.padEnd(12)} ${b.origin.padEnd(14)} ${state}\n`);
1000
+ stdout.write(DIM(` ${b.command}${b.version ? ' · ' + b.version : ''}\n`));
1001
+ if (!b.healthy && b.unhealthyReason)
1002
+ stdout.write(DIM(` ${b.unhealthyReason}\n`));
1003
+ }
1004
+ const owned = await ownedInstance(homeDir());
1005
+ if (owned && owned.reachable) {
1006
+ stdout.write(` hmh 专用实例运行中: pid ${owned.instance.pid} · CDP 127.0.0.1:${owned.instance.port}(智能体 browser_* 工具驱动它;停止: hmh browser stop)\n`);
1007
+ }
1008
+ else {
1009
+ stdout.write(' hmh 专用实例未运行(hmh browser start 启动;智能体首次使用 browser_* 工具时也会自动启动)\n');
1010
+ }
1011
+ const run = await detectRunning();
1012
+ if (run.running)
1013
+ stdout.write(` 另检测到你的日常 BrowserOS 在运行: CDP :${run.cdpPort} · MCP :${run.mcpPort}(hmh 不驱动日常实例——专用实例独立运行)\n`);
1014
+ return;
1015
+ }
1016
+ if (sub === 'trust' || sub === 'untrust') {
1017
+ const id = rest[1];
1018
+ if (!id) {
1019
+ stdout.write(`用法: hmh browser ${sub} <id>(见 hmh browser status)\n`);
1020
+ return;
1021
+ }
1022
+ if (sub === 'untrust') {
1023
+ const ok = await untrustBrowser(homeDir(), id);
1024
+ stdout.write(ok ? `已撤销 ${id} 的信任\n` : `${id} 本就未信任\n`);
1025
+ return;
1026
+ }
1027
+ const b = discoverBrowsers().find((x) => x.id === id);
1028
+ if (!b) {
1029
+ stdout.write(`未发现浏览器 '${id}'(hmh browser status 查看可用项)\n`);
1030
+ return;
1031
+ }
1032
+ const r = await trustBrowser(homeDir(), b);
1033
+ if (!r.ok) {
1034
+ stdout.write(`信任失败: ${r.error}\n`);
1035
+ return;
1036
+ }
1037
+ stdout.write(`已信任 ${id}(${b.origin})· sha256 钉住 ${r.sha256.slice(0, 16)}…\n`);
1038
+ stdout.write(DIM(' BrowserOS 官方自更新会改变哈希——变更后需重新 trust;撤销: hmh browser untrust ' + id + '\n'));
1039
+ return;
1040
+ }
1041
+ if (sub === 'start') {
1042
+ const portArg = rest.find((a) => a.startsWith('--port='));
1043
+ try {
1044
+ const inst = await startBrowser(homeDir(), { port: portArg ? Number(portArg.slice(7)) : undefined });
1045
+ stdout.write(`BrowserOS 已启动: pid ${inst.pid} · CDP 127.0.0.1:${inst.port} · 专属 profile ${inst.profileDir}\n`);
1046
+ stdout.write(DIM(' 智能体的 browser_* 工具驱动此实例;停止: hmh browser stop\n'));
1047
+ }
1048
+ catch (err) {
1049
+ stdout.write(`启动失败: ${String(err instanceof Error ? err.message : err).slice(0, 300)}\n`);
1050
+ }
1051
+ return;
1052
+ }
1053
+ if (sub === 'stop') {
1054
+ const r = await stopBrowser(homeDir());
1055
+ stdout.write(`${r.stopped ? '已停止' : '未停止'}: ${r.detail}\n`);
1056
+ return;
1057
+ }
1058
+ if (sub === 'open') {
1059
+ const url = rest[1];
1060
+ if (!url || !/^https?:\/\//i.test(url)) {
1061
+ stdout.write('用法: hmh browser open <https-url>(启动专用实例并打开页面)\n');
1062
+ return;
1063
+ }
1064
+ try {
1065
+ const inst = await startBrowser(homeDir());
1066
+ const { CdpBrowser } = await import('@hmharness/browser');
1067
+ const client = new CdpBrowser({ port: inst.port });
1068
+ const targetId = await client.openTab(url);
1069
+ await client.activateTab(targetId);
1070
+ stdout.write(`已在专用实例打开: ${url}\n`);
1071
+ }
1072
+ catch (err) {
1073
+ stdout.write(`打开失败: ${String(err instanceof Error ? err.message : err).slice(0, 300)}\n`);
1074
+ }
1075
+ return;
1076
+ }
1077
+ stdout.write('用法: hmh browser status | trust <id> | untrust <id> | start [--port=N] | stop | open <url> — BrowserOS 发现/信任/生命周期\n');
1078
+ return;
1079
+ }
964
1080
  if (cmd === 'cognitive') {
965
1081
  // Cognitive OS (blueprint 2026-09): read-only status one-pager. The
966
1082
  // subsystems are libraries first — they come alive when the agent loop
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cli",
3
- "version": "0.23.20",
3
+ "version": "0.23.22",
4
4
  "description": "hmharness command line: one-shot tasks, an interactive REPL, a fullscreen TUI, the web frontend, and direct tool invocation.",
5
5
  "type": "module",
6
6
  "main": "dist/main.js",
@@ -44,17 +44,19 @@
44
44
  "build": "tsc -p tsconfig.build.json"
45
45
  },
46
46
  "dependencies": {
47
- "@hmharness/agent": "0.23.20",
48
- "@hmharness/cognitive": "0.23.20",
49
- "@hmharness/domain-harmony": "0.23.20",
50
- "@hmharness/domain-ops": "0.23.20",
51
- "@hmharness/environments": "0.23.20",
52
- "@hmharness/evaluation": "0.23.20",
53
- "@hmharness/evolution": "0.23.20",
54
- "@hmharness/kernel": "0.23.20",
55
- "@hmharness/observability": "0.23.20",
56
- "@hmharness/sandbox": "0.23.20",
57
- "@hmharness/web": "0.23.20",
58
- "qrcode": "^1.5.4"
47
+ "@hmharness/agent": "0.23.22",
48
+ "@hmharness/browser": "0.23.22",
49
+ "@hmharness/cognitive": "0.23.22",
50
+ "@hmharness/domain-harmony": "0.23.22",
51
+ "@hmharness/domain-ops": "0.23.22",
52
+ "@hmharness/environments": "0.23.22",
53
+ "@hmharness/evaluation": "0.23.22",
54
+ "@hmharness/evolution": "0.23.22",
55
+ "@hmharness/kernel": "0.23.22",
56
+ "@hmharness/observability": "0.23.22",
57
+ "@hmharness/sandbox": "0.23.22",
58
+ "@hmharness/web": "0.23.22",
59
+ "qrcode": "^1.5.4",
60
+ "@hmharness/lsp": "0.23.22"
59
61
  }
60
62
  }