@hmharness/cli 0.23.20 → 0.23.21
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/dist/acp-serve.d.ts +62 -0
- package/dist/acp-serve.js +495 -0
- package/dist/main.js +116 -0
- package/package.json +15 -13
|
@@ -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 content-baseline whose tabs are ALL blank
|
|
4
|
+
* (the host's per-connection workspace windows — whenever they appeared).
|
|
5
|
+
* A window with real content is never touched. Returns how many closed;
|
|
6
|
+
* never throws (best-effort sweep). */
|
|
7
|
+
export declare function recycleBlankWindows(port: number, contentBaseline: 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,495 @@
|
|
|
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 content-baseline whose tabs are ALL blank
|
|
104
|
+
* (the host's per-connection workspace windows — whenever they appeared).
|
|
105
|
+
* A window with real content is never touched. Returns how many closed;
|
|
106
|
+
* never throws (best-effort sweep). */
|
|
107
|
+
export async function recycleBlankWindows(port, contentBaseline) {
|
|
108
|
+
try {
|
|
109
|
+
const current = await listHostWindows(port);
|
|
110
|
+
let closed = 0;
|
|
111
|
+
for (const windowId of current) {
|
|
112
|
+
if (contentBaseline.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: true — the ACP session id IS the hmh rollout id, so
|
|
205
|
+
// the host can reconnect a prior conversation instead of spawning a
|
|
206
|
+
// fresh agent (and, under BrowserOS Agent Mode, a fresh window)
|
|
207
|
+
// for every message.
|
|
208
|
+
ok({
|
|
209
|
+
protocolVersion: m.params?.protocolVersion ?? '0',
|
|
210
|
+
agentCapabilities: { loadSession: true },
|
|
211
|
+
authMethods: [],
|
|
212
|
+
});
|
|
213
|
+
await opts.onInitialized?.().catch(() => undefined);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
case 'authenticate': {
|
|
217
|
+
ok({});
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
case 'session/new': {
|
|
221
|
+
const rawCwd = typeof m.params?.cwd === 'string' ? m.params.cwd : '';
|
|
222
|
+
const cwd = isAbsolute(rawCwd) && existsSync(rawCwd) ? rawCwd : process.cwd();
|
|
223
|
+
const sessionId = await createRollout(resolve(cwd));
|
|
224
|
+
sessions.set(sessionId, { cwd: resolve(cwd), hmhId: sessionId });
|
|
225
|
+
ok({ sessionId });
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
case 'session/load': {
|
|
229
|
+
const sid = typeof m.params?.sessionId === 'string' ? m.params.sessionId : '';
|
|
230
|
+
if (!sid) {
|
|
231
|
+
err(m.id, -32602, 'session/load needs sessionId');
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (!sessions.has(sid)) {
|
|
235
|
+
const rawCwd = typeof m.params?.cwd === 'string' ? m.params.cwd : '';
|
|
236
|
+
const cwd = isAbsolute(rawCwd) && existsSync(rawCwd) ? resolve(rawCwd) : process.cwd();
|
|
237
|
+
// restore the transcript from the hmh rollout; a missing/cleaned
|
|
238
|
+
// rollout still loads (the runner falls back to a fresh session)
|
|
239
|
+
sessions.set(sid, { cwd, hmhId: sid, messages: await loadRollout(sid) });
|
|
240
|
+
}
|
|
241
|
+
ok({ sessionId: sid });
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
case 'session/set_mode': {
|
|
245
|
+
ok({});
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
case 'session/cancel': {
|
|
249
|
+
const sid = m.params?.sessionId;
|
|
250
|
+
if (sid)
|
|
251
|
+
sessions.get(sid)?.abort?.abort();
|
|
252
|
+
return; // notification
|
|
253
|
+
}
|
|
254
|
+
case 'session/prompt': {
|
|
255
|
+
const sid = m.params?.sessionId;
|
|
256
|
+
const session = sid ? sessions.get(sid) : undefined;
|
|
257
|
+
if (!session) {
|
|
258
|
+
err(m.id, -32602, `unknown session ${sid ?? '(none)'}`);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (session.abort) {
|
|
262
|
+
err(m.id, -32000, 'a prompt is already running in this session');
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const blocks = Array.isArray(m.params?.prompt) ? m.params.prompt : [];
|
|
266
|
+
const prompt = blocks.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim();
|
|
267
|
+
if (!prompt) {
|
|
268
|
+
err(m.id, -32602, 'prompt contained no text');
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
session.abort = new AbortController();
|
|
272
|
+
let seq = 0;
|
|
273
|
+
const toolIds = new Map(); // name -> stack of live ids
|
|
274
|
+
const cfg = await loadConfig().catch(() => undefined);
|
|
275
|
+
const auto = cfg?.approval === 'auto';
|
|
276
|
+
const events = {
|
|
277
|
+
onDelta(kind, chunk) {
|
|
278
|
+
if (!chunk)
|
|
279
|
+
return;
|
|
280
|
+
update(sid, {
|
|
281
|
+
sessionUpdate: kind === 'reasoning' ? 'agent_thought_chunk' : 'agent_message_chunk',
|
|
282
|
+
content: { type: 'text', text: chunk },
|
|
283
|
+
});
|
|
284
|
+
},
|
|
285
|
+
onToolCall(name, args) {
|
|
286
|
+
const id = `tc_${++seq}`;
|
|
287
|
+
const stack = toolIds.get(name) ?? [];
|
|
288
|
+
stack.push(id);
|
|
289
|
+
toolIds.set(name, stack);
|
|
290
|
+
update(sid, {
|
|
291
|
+
sessionUpdate: 'tool_call',
|
|
292
|
+
toolCallId: id,
|
|
293
|
+
title: titleFor(name, args),
|
|
294
|
+
kind: kindFor(name),
|
|
295
|
+
status: 'pending',
|
|
296
|
+
rawInput: args,
|
|
297
|
+
});
|
|
298
|
+
},
|
|
299
|
+
onToolResult(name, output, isError) {
|
|
300
|
+
const id = toolIds.get(name)?.pop();
|
|
301
|
+
if (!id)
|
|
302
|
+
return;
|
|
303
|
+
const text = output.slice(0, 2000);
|
|
304
|
+
update(sid, {
|
|
305
|
+
sessionUpdate: 'tool_call_update',
|
|
306
|
+
toolCallId: id,
|
|
307
|
+
status: isError ? 'failed' : 'completed',
|
|
308
|
+
content: [{ type: 'content', content: { type: 'text', text } }],
|
|
309
|
+
rawOutput: { text, isError },
|
|
310
|
+
});
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
const approvalAsk = auto ? undefined : async (toolName, args) => {
|
|
314
|
+
try {
|
|
315
|
+
const r = (await io.request('session/request_permission', {
|
|
316
|
+
sessionId: sid,
|
|
317
|
+
toolCall: {
|
|
318
|
+
toolCallId: `perm_${++seq}`,
|
|
319
|
+
title: titleFor(toolName, args),
|
|
320
|
+
kind: kindFor(toolName),
|
|
321
|
+
status: 'pending',
|
|
322
|
+
rawInput: args,
|
|
323
|
+
},
|
|
324
|
+
options: [
|
|
325
|
+
{ kind: 'allow_once', name: 'Allow', optionId: 'allow' },
|
|
326
|
+
{ kind: 'reject_once', name: 'Reject', optionId: 'reject' },
|
|
327
|
+
],
|
|
328
|
+
}));
|
|
329
|
+
return r?.outcome?.outcome === 'selected' && r.outcome.optionId === 'allow';
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
return false; // host without permission UI / round-trip failed: deny
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
try {
|
|
336
|
+
const r = await runTask({
|
|
337
|
+
prompt,
|
|
338
|
+
cwd: session.cwd,
|
|
339
|
+
sessionId: session.hmhId,
|
|
340
|
+
resumeMessages: session.messages,
|
|
341
|
+
signal: session.abort.signal,
|
|
342
|
+
events,
|
|
343
|
+
approvalAsk,
|
|
344
|
+
});
|
|
345
|
+
session.hmhId = r.sessionId;
|
|
346
|
+
session.messages = r.messages;
|
|
347
|
+
ok({ stopReason: session.abort.signal.aborted ? 'cancelled' : 'end_turn' });
|
|
348
|
+
}
|
|
349
|
+
catch (e) {
|
|
350
|
+
// the turn still completes — with an honest error message in the
|
|
351
|
+
// chat rather than a bare protocol error the panel can't render
|
|
352
|
+
update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `\n[error] ${String(e instanceof Error ? e.message : e).slice(0, 400)}` } });
|
|
353
|
+
ok({ stopReason: session.abort.signal.aborted ? 'cancelled' : 'end_turn' });
|
|
354
|
+
}
|
|
355
|
+
finally {
|
|
356
|
+
session.abort = undefined;
|
|
357
|
+
// stopReason is already out; now sweep the blank workspace windows
|
|
358
|
+
// this connection caused (never blocks the protocol >8s)
|
|
359
|
+
await Promise.race([opts.onTurnSettled?.().catch(() => undefined), new Promise((r) => setTimeout(r, 8_000))]);
|
|
360
|
+
}
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
default: {
|
|
364
|
+
if (isRequest)
|
|
365
|
+
err(m.id, -32601, `method not found: ${m.method}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return { handle, sessions };
|
|
370
|
+
}
|
|
371
|
+
/** Wire the protocol core to real stdio. Exits when stdin closes. */
|
|
372
|
+
export async function serveAcp() {
|
|
373
|
+
// stdout is the protocol channel: silence any library prints.
|
|
374
|
+
const realLog = console.log;
|
|
375
|
+
console.log = (...a) => console.error(...a);
|
|
376
|
+
void realLog;
|
|
377
|
+
// Host-browser attach: when spawned by BrowserOS's ACP host, its managed
|
|
378
|
+
// CDP port is recorded in ~/.browseros/server.json — the browser_* tools
|
|
379
|
+
// then drive the user's REAL tabs (their pages, their logins) instead of
|
|
380
|
+
// spawning a dedicated instance (which would pop a SECOND browser window
|
|
381
|
+
// next to the one the user is talking to us from). Standalone acp-serve
|
|
382
|
+
// (Zed etc.) finds no marker and keeps the dedicated-instance design.
|
|
383
|
+
try {
|
|
384
|
+
const { readFile } = await import('node:fs/promises');
|
|
385
|
+
const { homedir } = await import('node:os');
|
|
386
|
+
const { join: pjoin } = await import('node:path');
|
|
387
|
+
const sj = JSON.parse(await readFile(pjoin(homedir(), '.browseros', 'server.json'), 'utf8'));
|
|
388
|
+
if (Number.isInteger(sj.cdp_port) && sj.cdp_port > 0)
|
|
389
|
+
process.env.HMH_BROWSER_ATTACH = String(sj.cdp_port);
|
|
390
|
+
}
|
|
391
|
+
catch { /* not under BrowserOS — standalone mode */ }
|
|
392
|
+
let nextReqId = 1;
|
|
393
|
+
const pending = new Map();
|
|
394
|
+
const write = (frame) => {
|
|
395
|
+
process.stdout.write(JSON.stringify(frame) + '\n');
|
|
396
|
+
};
|
|
397
|
+
const io = {
|
|
398
|
+
send: write,
|
|
399
|
+
request(method, params) {
|
|
400
|
+
const id = nextReqId++;
|
|
401
|
+
return new Promise((resolve, reject) => {
|
|
402
|
+
pending.set(id, { resolve, reject });
|
|
403
|
+
write({ jsonrpc: '2.0', id, method, params });
|
|
404
|
+
});
|
|
405
|
+
},
|
|
406
|
+
};
|
|
407
|
+
// window-recycling hooks (only under a host browser). The host gives
|
|
408
|
+
// every new agent connection a blank workspace window; the baseline is
|
|
409
|
+
// the set of CONTENT windows (safe to keep forever), and each sweep
|
|
410
|
+
// closes any blank window outside it — regardless of when it appeared
|
|
411
|
+
// (the host may open ours before the handshake OR after the turn — hence
|
|
412
|
+
// the delayed second sweep). Every action lands in a log file so a
|
|
413
|
+
// recurrence is diagnosable from disk.
|
|
414
|
+
const attachPort = Number(process.env.HMH_BROWSER_ATTACH ?? 0);
|
|
415
|
+
let contentBaseline = null;
|
|
416
|
+
const recycleLog = async (msg) => {
|
|
417
|
+
console.error(`[acp-window] ${msg}`);
|
|
418
|
+
try {
|
|
419
|
+
const { appendFile, mkdir } = await import('node:fs/promises');
|
|
420
|
+
const logsDir = join(homeDir(), 'logs');
|
|
421
|
+
await mkdir(logsDir, { recursive: true });
|
|
422
|
+
await appendFile(join(logsDir, 'acp-window.log'), `${new Date().toISOString()} pid=${process.pid} ${msg}\n`, 'utf8');
|
|
423
|
+
}
|
|
424
|
+
catch { /* logging is best-effort */ }
|
|
425
|
+
};
|
|
426
|
+
const sweep = async (why) => {
|
|
427
|
+
if (!contentBaseline) {
|
|
428
|
+
await recycleLog(`${why}: baseline unavailable — sweep skipped`);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
const closed = await recycleBlankWindows(attachPort, contentBaseline);
|
|
432
|
+
contentBaseline = await listContentWindows(attachPort).catch(() => contentBaseline);
|
|
433
|
+
await recycleLog(`${why}: closed=${closed} contentWindows=${contentBaseline?.size ?? '?'}`);
|
|
434
|
+
};
|
|
435
|
+
const hooks = Number.isInteger(attachPort) && attachPort > 0
|
|
436
|
+
? {
|
|
437
|
+
onInitialized: async () => {
|
|
438
|
+
contentBaseline = await listContentWindows(attachPort).catch(() => null);
|
|
439
|
+
await recycleLog(`initialize: contentWindows=${contentBaseline?.size ?? 'unavailable'}`);
|
|
440
|
+
// opening sweep: recycle whatever blank windows earlier
|
|
441
|
+
// connections left behind (the host may hard-kill us between
|
|
442
|
+
// messages — taskkill gives no stdin-close cleanup chance)
|
|
443
|
+
await sweep('opening');
|
|
444
|
+
},
|
|
445
|
+
onTurnSettled: async () => {
|
|
446
|
+
await sweep('turn-settled');
|
|
447
|
+
// the host sometimes opens the workspace window AFTER the stop
|
|
448
|
+
// response — sweep again shortly, fire-and-forget
|
|
449
|
+
void (async () => {
|
|
450
|
+
await new Promise((r) => setTimeout(r, 2_500));
|
|
451
|
+
await sweep('turn-settled+2.5s').catch(() => undefined);
|
|
452
|
+
})();
|
|
453
|
+
},
|
|
454
|
+
}
|
|
455
|
+
: {};
|
|
456
|
+
const server = createAcpServer({ io, ...hooks });
|
|
457
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
458
|
+
rl.on('line', (line) => {
|
|
459
|
+
const text = line.trim();
|
|
460
|
+
if (!text)
|
|
461
|
+
return;
|
|
462
|
+
let msg;
|
|
463
|
+
try {
|
|
464
|
+
msg = JSON.parse(text);
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
console.error('[acp] unparseable frame:', text.slice(0, 120));
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
// responses to OUR agent→client requests (permissions)
|
|
471
|
+
if ((msg.id !== undefined) && !('method' in msg)) {
|
|
472
|
+
const entry = pending.get(Number(msg.id));
|
|
473
|
+
if (entry) {
|
|
474
|
+
pending.delete(Number(msg.id));
|
|
475
|
+
const r = msg;
|
|
476
|
+
if (r.error)
|
|
477
|
+
entry.reject(new Error(r.error.message ?? 'request error'));
|
|
478
|
+
else
|
|
479
|
+
entry.resolve(r.result);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
void server.handle(msg).catch((e) => console.error('[acp] handler error:', e));
|
|
484
|
+
});
|
|
485
|
+
return new Promise((resolve) => {
|
|
486
|
+
rl.on('close', async () => {
|
|
487
|
+
for (const [, p] of pending)
|
|
488
|
+
p.reject(new Error('client disconnected'));
|
|
489
|
+
// last-chance sweep: the host disposes us between messages, and the
|
|
490
|
+
// workspace window it gave this connection would otherwise linger
|
|
491
|
+
await Promise.race([sweep('disconnect'), new Promise((r) => setTimeout(r, 6_000))]);
|
|
492
|
+
resolve();
|
|
493
|
+
});
|
|
494
|
+
});
|
|
495
|
+
}
|
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.
|
|
3
|
+
"version": "0.23.21",
|
|
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.
|
|
48
|
-
"@hmharness/
|
|
49
|
-
"@hmharness/
|
|
50
|
-
"@hmharness/domain-
|
|
51
|
-
"@hmharness/
|
|
52
|
-
"@hmharness/
|
|
53
|
-
"@hmharness/
|
|
54
|
-
"@hmharness/
|
|
55
|
-
"@hmharness/
|
|
56
|
-
"@hmharness/
|
|
57
|
-
"@hmharness/
|
|
58
|
-
"
|
|
47
|
+
"@hmharness/agent": "0.23.21",
|
|
48
|
+
"@hmharness/browser": "0.23.21",
|
|
49
|
+
"@hmharness/cognitive": "0.23.21",
|
|
50
|
+
"@hmharness/domain-harmony": "0.23.21",
|
|
51
|
+
"@hmharness/domain-ops": "0.23.21",
|
|
52
|
+
"@hmharness/environments": "0.23.21",
|
|
53
|
+
"@hmharness/evaluation": "0.23.21",
|
|
54
|
+
"@hmharness/evolution": "0.23.21",
|
|
55
|
+
"@hmharness/kernel": "0.23.21",
|
|
56
|
+
"@hmharness/observability": "0.23.21",
|
|
57
|
+
"@hmharness/sandbox": "0.23.21",
|
|
58
|
+
"@hmharness/web": "0.23.21",
|
|
59
|
+
"qrcode": "^1.5.4",
|
|
60
|
+
"@hmharness/lsp": "0.23.21"
|
|
59
61
|
}
|
|
60
62
|
}
|