@hmharness/cli 0.23.37 → 0.23.39

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.
@@ -63,9 +63,9 @@ let PACKAGES = ['cli', 'web', 'agent', 'kernel', 'sandbox', 'evolution',
63
63
  // The release bot keeps versions synced; the NAMES must cover the full
64
64
  // first-party set so the offline path cannot produce an incomplete tree.
65
65
  const FALLBACK_PINS = {
66
- cli: '0.23.37', web: '0.23.37', agent: '0.23.37', kernel: '0.23.37',
67
- sandbox: '0.23.37', evolution: '0.23.37', 'domain-ops': '0.23.37',
68
- evaluation: '0.23.37', observability: '0.23.37', 'domain-harmony': '0.23.37',
66
+ cli: '0.23.39', web: '0.23.39', agent: '0.23.39', kernel: '0.23.39',
67
+ sandbox: '0.23.39', evolution: '0.23.39', 'domain-ops': '0.23.39',
68
+ evaluation: '0.23.39', observability: '0.23.39', 'domain-harmony': '0.23.39',
69
69
  };
70
70
 
71
71
  // ---------- helpers ---------------------------------------------------------
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @hmharness/cli - extension chat via the REAL agent (round 52)
3
+ *
4
+ * The user's side-by-side verdict: the BrowserOS panel (hmh acp-serve) and
5
+ * the extension sidebar were "the same hmh CLI AI" in name only — acp-serve
6
+ * runs runAgentTask (full tool registry + the real system prompt with
7
+ * memory/skills/insights + session continuity), while the sidebar was a
8
+ * hand-rolled chat loop. This module converges them: one chat turn = one
9
+ * runAgentTask on a per-origin SESSION (conversations continue like a real
10
+ * agent thread), tools/events/approval wired:
11
+ * - events.onToolCall/onToolResult → the live activity feed
12
+ * - approvalAsk → the conversational confirm gate: deny now, record the
13
+ * exact call, the user's 「确认」 next turn executes it pre-loop and
14
+ * injects the result (identical contract to the compact brain)
15
+ * - proactive page context rides as task prefix (round 48 discipline)
16
+ * - wall-clock abort at the segment boundary → auto-continue sentinel
17
+ */
18
+ import type { ChatTurnInput, PageAct } from '@hmharness/extension';
19
+ import type { Registry, ToolContext } from '@hmharness/kernel';
20
+ /** what serve injects: the agent machinery + the bridge page channel */
21
+ export interface AgentBrainEnv {
22
+ buildRegistry: () => Promise<{
23
+ reg: Registry;
24
+ }>;
25
+ /** native-only rebuild (no MCP servers) for the degraded path */
26
+ buildRegistryNative?: () => Promise<{
27
+ reg: Registry;
28
+ }>;
29
+ runAgentTask: (opts: Record<string, unknown>) => Promise<{
30
+ text: string;
31
+ turns: number;
32
+ toolUses: number;
33
+ sessionId: string;
34
+ }>;
35
+ ctx: ToolContext;
36
+ /** bridge page channel: goto + proactive read (http/https enforced bridge-side) */
37
+ goto: (url: string) => Promise<unknown>;
38
+ readPage: () => Promise<unknown>;
39
+ step: (line: string) => void;
40
+ log?: (line: string) => void;
41
+ /** per-request wall clock (tests inject milliseconds) */
42
+ segmentMs?: number;
43
+ }
44
+ /** One chat turn = one real agent task on the origin's session. */
45
+ export declare function answerWithAgentTurn(input: ChatTurnInput, env: AgentBrainEnv): Promise<string>;
46
+ /** the compact fallback path stays for brain-less/agent-less environments */
47
+ export type CompactDeps = {
48
+ readPage: () => Promise<unknown>;
49
+ act: (act: PageAct) => Promise<unknown>;
50
+ };
@@ -0,0 +1,119 @@
1
+ import { formatPageSnapshot, summarizePage } from '@hmharness/extension';
2
+ /** per-origin agent state: session id (conversation continuity) + the last
3
+ * approval the user was asked to confirm (name+args, executed on 「确认」) */
4
+ const sessions = new Map();
5
+ const agentPending = new Map();
6
+ const CONFIRM_RE = /^(确认|确定|执行|同意|yes|ok)\s*$/i;
7
+ const SEGMENT_MS = 360_000;
8
+ const pageGotoTool = (goto) => ({
9
+ name: 'page_goto',
10
+ description: '把用户浏览器当前标签页导航到指定网址(http/https)。需要换页面时直接用。',
11
+ parameters: {
12
+ type: 'object',
13
+ properties: { url: { type: 'string', description: '完整网址,必须 http(s)://' } },
14
+ required: ['url'],
15
+ },
16
+ async execute(args) {
17
+ const url = String(args.url ?? '');
18
+ if (!/^https?:\/\//i.test(url))
19
+ return { output: 'page_goto 只允许 http/https 地址', isError: true };
20
+ return { output: JSON.stringify(await goto(url)).slice(0, 2000) };
21
+ },
22
+ });
23
+ async function pageContext(env) {
24
+ try {
25
+ const raw = await env.readPage();
26
+ if (!raw || typeof raw !== 'object')
27
+ return '';
28
+ return `\n\n【用户当前浏览器页面 · 自动附上】\n${formatPageSnapshot(summarizePage(raw)).slice(0, 6000)}`;
29
+ }
30
+ catch {
31
+ return ''; // proactive context is a bonus, never a blocker
32
+ }
33
+ }
34
+ /** One chat turn = one real agent task on the origin's session. */
35
+ export async function answerWithAgentTurn(input, env) {
36
+ const origin = input.origin ?? 'anon';
37
+ env.step('组装工具注册表…');
38
+ let reg;
39
+ try {
40
+ reg = (await Promise.race([
41
+ env.buildRegistry(),
42
+ new Promise((_, rej) => setTimeout(() => rej(new Error('registry build timeout (30s)')), 30_000)),
43
+ ])).reg;
44
+ }
45
+ catch (err) {
46
+ // a dead/slow MCP server must not black-hole the FIRST turn of a fresh
47
+ // daemon (field-caught round 53: 888s of silence before any step) —
48
+ // degrade to the native registry (everything except MCP tools)
49
+ env.step(`注册表组装超时——降级为原生工具集(不含 MCP)`);
50
+ if (!env.buildRegistryNative)
51
+ throw err;
52
+ reg = (await Promise.race([
53
+ env.buildRegistryNative(),
54
+ new Promise((_, rej) => setTimeout(() => rej(new Error('native fallback timeout')), 15_000)),
55
+ ])).reg;
56
+ }
57
+ env.step('注册表就绪');
58
+ // the bridge page channel joins the real registry (idempotent by name)
59
+ try {
60
+ reg.register(pageGotoTool(env.goto));
61
+ }
62
+ catch { /* already there */ }
63
+ // resolve last turn's pending approval: 「确认」 executes it pre-loop
64
+ let prefix = '';
65
+ const pending = agentPending.get(origin);
66
+ agentPending.delete(origin);
67
+ if (pending) {
68
+ if (CONFIRM_RE.test(input.message.trim())) {
69
+ env.step(`确认执行: ${pending.summary}`);
70
+ env.log?.(`侧栏确认执行(agent): ${pending.summary}`);
71
+ try {
72
+ const r = await pending.reg.get(pending.name)?.execute(pending.args, pending.ctx);
73
+ prefix = `【已执行: ${pending.summary}】\n${String(r?.output ?? '').slice(0, 4000)}\n\n`;
74
+ }
75
+ catch (err) {
76
+ prefix = `【执行失败: ${pending.summary}】${String(err instanceof Error ? err.message : err).slice(0, 300)}\n\n`;
77
+ }
78
+ }
79
+ else {
80
+ prefix = `【已取消: ${pending.summary}(用户未确认)】\n\n`;
81
+ }
82
+ }
83
+ const task = `${prefix}${input.message}${await pageContext(env)}`;
84
+ const sessionId = sessions.get(origin);
85
+ const ac = new AbortController();
86
+ const bail = setTimeout(() => { try {
87
+ ac.abort();
88
+ }
89
+ catch { /* gone */ } }, env.segmentMs ?? SEGMENT_MS);
90
+ try {
91
+ const r = await env.runAgentTask({
92
+ task,
93
+ registry: reg,
94
+ ctx: env.ctx,
95
+ ...(sessionId ? { sessionId } : {}),
96
+ signal: ac.signal,
97
+ events: {
98
+ onToolCall: (name, args) => env.step(`工具 ${name}: ${JSON.stringify(args).slice(0, 80)}`),
99
+ onToolResult: (name, output, isError) => env.step(isError ? `${name} 失败: ${output.slice(0, 80)}` : `${name} 完成`),
100
+ },
101
+ approvalAsk: async (name, args) => {
102
+ const summary = `${name} ${JSON.stringify(args).slice(0, 100)}`;
103
+ agentPending.set(origin, { name, args, summary, reg, ctx: env.ctx });
104
+ env.step(`待确认: ${summary}`);
105
+ return false; // the model relays the ask; 「确认」 executes next turn
106
+ },
107
+ });
108
+ sessions.set(origin, r.sessionId);
109
+ return r.text?.trim() || '(模型返回了空回复)';
110
+ }
111
+ catch (err) {
112
+ if (ac.signal.aborted)
113
+ return '(这一段到达时间边界,已收尾——任务未完,自动继续。)\n[[hmh:auto-continue]]';
114
+ throw err;
115
+ }
116
+ finally {
117
+ clearTimeout(bail);
118
+ }
119
+ }
@@ -1,21 +1,42 @@
1
1
  /**
2
- * @hmharness/cli - extension chat brain (round 45)
2
+ * @hmharness/cli - extension chat brain (rounds 45/48/49)
3
3
  *
4
- * The other end of the browser-side chat panel: a compact tool-loop agent
5
- * turn that reads/acts on the user's CURRENT tab through the live bridge and
6
- * answers with the user's configured provider (routing 'chat' — the same
7
- * one the web UI and CLI agent use). One HTTP request = one turn; the
8
- * transcript between turns lives in the bridge (in-memory).
4
+ * The other end of the browser-side chat panel: an agent turn that HAS the
5
+ * current page (proactive pre-read, round 48) plus — when the serve process
6
+ * wires them — navigation, tabs, workspace files and shell commands (round
7
+ * 49: the user called the two-tool version "crippled"; this is the full
8
+ * hmharness capability set, with a CONVERSATIONAL approval gate for the
9
+ * dangerous ones: the model proposes, the user types 「确认」).
9
10
  */
10
11
  import { chat, type ProviderConfig } from '@hmharness/kernel';
11
12
  import type { ChatTurnInput, PageAct } from '@hmharness/extension';
12
13
  export interface ChatBrainDeps {
13
14
  readPage: () => Promise<unknown>;
14
15
  act: (act: PageAct) => Promise<unknown>;
15
- /** audit line sink — page_act is user-visible but still logged */
16
+ /** audit line sink — page_act and confirmed commands are logged */
16
17
  log?: (line: string) => void;
18
+ /** navigate the user's active tab (http/https enforced both ends) */
19
+ goto?: (url: string) => Promise<unknown>;
20
+ listTabs?: () => Promise<unknown>;
21
+ /** shell — ToolResult-shaped { output, isError? } from the agent's runCommandTool */
22
+ runCommand?: (command: string, timeoutMs?: number) => Promise<unknown>;
23
+ readFile?: (path: string) => Promise<unknown>;
24
+ writeFile?: (path: string, content: string) => Promise<unknown>;
25
+ listDir?: (path: string) => Promise<unknown>;
26
+ /** the working directory commands/files resolve against (told to the model) */
27
+ workspace?: string;
28
+ /** LIVE activity feed (round 50): every step lands in the panel while it waits */
29
+ step?: (line: string) => void;
17
30
  }
31
+ /** PROACTIVE page context (round 48): read the user's current tab BEFORE the
32
+ * model runs, so even a tool-call-less model already HAS the page. A failed
33
+ * read becomes an honest note in the prompt, never a silent blank. */
34
+ /** PROACTIVE page context (round 48): read the user's current tab BEFORE the
35
+ * model runs, so even a tool-call-less model already HAS the page. A failed
36
+ * read becomes an honest note in the prompt, never a silent blank.
37
+ * Takes only the readPage sliver — the full brain deps are not needed. */
38
+ export declare function readPageContext(deps: Pick<ChatBrainDeps, 'readPage'>): Promise<string>;
18
39
  /** Run ONE conversational turn (message + history → reply string). */
19
40
  export declare function answerChatTurn(input: ChatTurnInput, deps: ChatBrainDeps): Promise<string>;
20
41
  /** The tool loop, separated so tests can inject a fake chat implementation. */
21
- export declare function runChatTurn(provider: ProviderConfig, input: ChatTurnInput, deps: ChatBrainDeps, chatImpl: typeof chat): Promise<string>;
42
+ export declare function runChatTurn(provider: ProviderConfig, input: ChatTurnInput, deps: ChatBrainDeps, chatImpl: typeof chat, origin?: string, maxRounds?: number, wallClockMs?: number): Promise<string>;
@@ -1,93 +1,312 @@
1
1
  /**
2
- * @hmharness/cli - extension chat brain (round 45)
2
+ * @hmharness/cli - extension chat brain (rounds 45/48/49)
3
3
  *
4
- * The other end of the browser-side chat panel: a compact tool-loop agent
5
- * turn that reads/acts on the user's CURRENT tab through the live bridge and
6
- * answers with the user's configured provider (routing 'chat' — the same
7
- * one the web UI and CLI agent use). One HTTP request = one turn; the
8
- * transcript between turns lives in the bridge (in-memory).
4
+ * The other end of the browser-side chat panel: an agent turn that HAS the
5
+ * current page (proactive pre-read, round 48) plus — when the serve process
6
+ * wires them — navigation, tabs, workspace files and shell commands (round
7
+ * 49: the user called the two-tool version "crippled"; this is the full
8
+ * hmharness capability set, with a CONVERSATIONAL approval gate for the
9
+ * dangerous ones: the model proposes, the user types 「确认」).
9
10
  */
10
11
  import { loadConfig, resolveProvider, chat } from '@hmharness/kernel';
11
- /** OpenAI-style function schemas the model sees. Structured args only —
12
- * no script text ever crosses this boundary (same rule as page.act). */
13
- const TOOLS = [
14
- {
15
- type: 'function',
16
- function: {
17
- name: 'page_read',
18
- description: '读取用户当前浏览器标签页:标题、URL 与正文文本的精简提取。回答任何关于"这个页面/当前页"的问题前先调用它。',
19
- parameters: { type: 'object', properties: {}, additionalProperties: false },
12
+ import { formatPageSnapshot, summarizePage } from '@hmharness/extension';
13
+ /** round bound: the CLI's own maxTurns guard, floored at 50 for the sidebar
14
+ * (round 49: hand over a task, get it FINISHED — the panel auto-continues
15
+ * past the budget via the sentinel, so the floor only guards one HTTP
16
+ * request against infinite loops, never the task). */
17
+ const DEFAULT_MAX_ROUNDS = 50;
18
+ /** pending confirmation per chat origin: the model proposed, we wait for 「确认」 */
19
+ const pendingConfirm = new Map();
20
+ const CONFIRM_RE = /^(确认|确定|执行|同意|yes|ok)\s*$/i;
21
+ function baseTools() {
22
+ return [
23
+ {
24
+ type: 'function',
25
+ function: {
26
+ name: 'page_read',
27
+ description: '重新读取用户当前浏览器标签页(内容可能已变)。回答页面问题前若已附有自动读取的内容,先基于它回答。',
28
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
29
+ },
20
30
  },
21
- },
22
- {
23
- type: 'function',
24
- function: {
25
- name: 'page_act',
26
- description: '操作用户当前标签页(click 点击 / type 输入 / scroll 滚动 / select 选择)。动作会在用户眼前执行;不确定时先用 page_read 看页面、再问用户。',
27
- parameters: {
28
- type: 'object',
29
- properties: {
30
- action: { type: 'string', enum: ['click', 'type', 'scroll', 'select'] },
31
- selector: { type: 'string', description: '目标元素的 CSS 选择器' },
32
- text: { type: 'string', description: 'action=type 时要输入的文本' },
33
- direction: { type: 'string', enum: ['up', 'down', 'top', 'bottom'], description: 'action=scroll 时的方向' },
31
+ {
32
+ type: 'function',
33
+ function: {
34
+ name: 'page_act',
35
+ description: '操作用户当前标签页(click/type/scroll/select)。动作会在用户眼前执行;不确定时先 page_read 看页面、再问用户。',
36
+ parameters: {
37
+ type: 'object',
38
+ properties: {
39
+ action: { type: 'string', enum: ['click', 'type', 'scroll', 'select'] },
40
+ selector: { type: 'string', description: '目标元素的 CSS 选择器' },
41
+ text: { type: 'string', description: 'action=type 时要输入的文本' },
42
+ direction: { type: 'string', enum: ['up', 'down', 'top', 'bottom'], description: 'action=scroll 时的方向' },
43
+ },
44
+ required: ['action'],
34
45
  },
35
- required: ['action'],
36
46
  },
37
47
  },
38
- },
39
- ];
40
- const MAX_ROUNDS = 6;
41
- function systemPrompt(input) {
48
+ ];
49
+ }
50
+ function extendedTools(deps) {
51
+ const tools = baseTools();
52
+ if (deps.goto) {
53
+ tools.push({
54
+ type: 'function',
55
+ function: {
56
+ name: 'page_goto',
57
+ description: '把用户当前标签页导航到指定网址(http/https)。页面打不开/需要换页面时直接用它,不要请用户手动开。',
58
+ parameters: { type: 'object', properties: { url: { type: 'string', description: '完整网址,必须 http(s)://' } }, required: ['url'] },
59
+ },
60
+ });
61
+ }
62
+ if (deps.listTabs) {
63
+ tools.push({
64
+ type: 'function',
65
+ function: {
66
+ name: 'tabs_list',
67
+ description: '列出用户浏览器当前打开的全部标签页。',
68
+ parameters: { type: 'object', properties: {} },
69
+ },
70
+ });
71
+ }
72
+ if (deps.runCommand) {
73
+ tools.push({
74
+ type: 'function',
75
+ function: {
76
+ name: 'run_command',
77
+ description: '在工作目录执行一条终端命令(npm/git 等)。危险操作会先征求用户确认——把确认提示原样转达给用户。',
78
+ parameters: {
79
+ type: 'object',
80
+ properties: { command: { type: 'string', description: '单行命令' }, timeout_ms: { type: 'number', description: '超时毫秒(默认 60000,最大 300000)' } },
81
+ required: ['command'],
82
+ },
83
+ },
84
+ });
85
+ }
86
+ if (deps.readFile) {
87
+ tools.push({
88
+ type: 'function',
89
+ function: {
90
+ name: 'read_file',
91
+ description: '读取工作目录中的文件内容。',
92
+ parameters: { type: 'object', properties: { path: { type: 'string', description: '文件路径' } }, required: ['path'] },
93
+ },
94
+ });
95
+ }
96
+ if (deps.listDir) {
97
+ tools.push({
98
+ type: 'function',
99
+ function: {
100
+ name: 'list_dir',
101
+ description: '列出工作目录中某路径下的内容。',
102
+ parameters: { type: 'object', properties: { path: { type: 'string', description: '目录路径(空 = 工作目录)' } }, required: ['path'] },
103
+ },
104
+ });
105
+ }
106
+ if (deps.writeFile) {
107
+ tools.push({
108
+ type: 'function',
109
+ function: {
110
+ name: 'write_file',
111
+ description: '写入/覆盖工作目录中的文件。会先征求用户确认。',
112
+ parameters: { type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path', 'content'] },
113
+ },
114
+ });
115
+ }
116
+ return tools;
117
+ }
118
+ function systemPrompt(input, pageBlock, deps) {
42
119
  const lines = [
43
- '你是 hmharness 浏览器助手,直接在用户浏览器侧栏的对话面板里工作。用简洁中文回答。',
44
- '工具:page_read 读取用户当前浏览的页面;page_act 操作该页面。页面类问题先 page_read 再答。',
120
+ '你是 hmharness 智能体的浏览器侧栏形态,用简洁中文工作。',
121
+ '页面能力:当前页面内容已自动附上;可用 page_read 重读、page_act 操作、page_goto 导航、tabs_list 列标签页。',
45
122
  ];
123
+ if (deps.runCommand) {
124
+ lines.push(`终端能力:工作目录 ${deps.workspace ?? '(serve 进程目录)'} 下可 run_command(执行命令)、read_file / write_file / list_dir(文件操作)。修改类与命令类操作需用户逐次确认——把确认提示原样转达,用户回复「确认」后才执行。`);
125
+ }
126
+ else {
127
+ lines.push('本会话未接入终端/文件能力(仅页面能力)。');
128
+ }
129
+ lines.push('页面打不开时先 page_goto,不要请用户手动操作。回答基于证据;做不到就明说。');
130
+ lines.push('任务策略:Dependabot/安全告警/CI 报错等通知类任务——邮件只是通知,病根在本地代码与依赖锁定文件里;直接用文件读写+命令在本地修复并 git 提交推送即可关闭远程告警,除非明确需要网页上的信息,否则不要去操作网页。');
46
131
  if (input.page?.url)
47
132
  lines.push(`用户当前标签页: ${input.page.title ?? '(无标题)'} — ${input.page.url}`);
133
+ if (pageBlock)
134
+ lines.push(pageBlock);
48
135
  return lines.join('\n');
49
136
  }
137
+ /** PROACTIVE page context (round 48): read the user's current tab BEFORE the
138
+ * model runs, so even a tool-call-less model already HAS the page. A failed
139
+ * read becomes an honest note in the prompt, never a silent blank. */
140
+ /** PROACTIVE page context (round 48): read the user's current tab BEFORE the
141
+ * model runs, so even a tool-call-less model already HAS the page. A failed
142
+ * read becomes an honest note in the prompt, never a silent blank.
143
+ * Takes only the readPage sliver — the full brain deps are not needed. */
144
+ export async function readPageContext(deps) {
145
+ try {
146
+ const raw = await deps.readPage();
147
+ if (!raw || typeof raw !== 'object')
148
+ return '【当前页面】读取无结果(受保护页面或站点权限未授予)。';
149
+ const text = formatPageSnapshot(summarizePage(raw)).slice(0, 6000);
150
+ return `【当前页面 · 自动读取】\n${text}`;
151
+ }
152
+ catch (err) {
153
+ return `【当前页面】自动读取失败: ${String(err instanceof Error ? err.message : err).slice(0, 150)}(浏览器内置页/受保护页面无法读取;可尝试 page_goto 到普通网页)`;
154
+ }
155
+ }
50
156
  /** Run ONE conversational turn (message + history → reply string). */
51
157
  export async function answerChatTurn(input, deps) {
52
158
  const cfg = await loadConfig();
53
159
  const provider = resolveProvider(cfg, 'chat');
54
160
  if (!provider?.apiKey)
55
161
  throw new Error('尚未配置 LLM provider — 在网页端设置或运行 hmh web 设置密钥后重试');
56
- return runChatTurn(provider, input, deps, chat);
162
+ const origin = input.origin ?? 'anon';
163
+ // pending-confirmation gate (round 49): 「确认」 executes, anything else cancels
164
+ const pending = pendingConfirm.get(origin);
165
+ pendingConfirm.delete(origin);
166
+ let executed = '';
167
+ if (pending) {
168
+ if (CONFIRM_RE.test(input.message.trim())) {
169
+ try {
170
+ const r = (await pending.run());
171
+ deps.log?.(`侧栏确认执行: ${pending.summary}`);
172
+ executed = `【已执行: ${pending.summary}】\n${String(r?.output ?? '').slice(0, 4000)}${r?.isError ? '\n(执行报错)' : ''}\n\n`;
173
+ }
174
+ catch (err) {
175
+ executed = `【执行失败: ${pending.summary}】${String(err instanceof Error ? err.message : err).slice(0, 300)}\n\n`;
176
+ }
177
+ }
178
+ else {
179
+ executed = `【已取消: ${pending.summary}(用户未确认)】\n\n`;
180
+ }
181
+ }
182
+ return runChatTurn(provider, { ...input, message: executed + input.message }, deps, chat, origin, Math.max(cfg.maxTurns ?? DEFAULT_MAX_ROUNDS, DEFAULT_MAX_ROUNDS));
57
183
  }
58
184
  /** The tool loop, separated so tests can inject a fake chat implementation. */
59
- export async function runChatTurn(provider, input, deps, chatImpl) {
185
+ export async function runChatTurn(provider, input, deps, chatImpl, origin = 'anon', maxRounds = DEFAULT_MAX_ROUNDS, wallClockMs = 360_000) {
186
+ const t0 = Date.now();
187
+ const step = (line) => { try {
188
+ deps.step?.(line);
189
+ }
190
+ catch { /* feed is best-effort */ } };
191
+ step('读取当前页面(预热)…');
192
+ let pageFails = 0; // page-channel damper: a ghost extension turns every
193
+ // page op into a full 20s timeout burn — after 3 consecutive failures the
194
+ // channel short-circuits so the loop pivots instead of grinding invisibly
60
195
  const messages = [
61
- { role: 'system', content: systemPrompt(input) },
196
+ { role: 'system', content: systemPrompt(input, await readPageContext(deps), deps) },
62
197
  ...input.history.map((t) => ({ role: t.role, content: t.content })),
63
198
  { role: 'user', content: input.message },
64
199
  ];
65
- for (let round = 0; round < MAX_ROUNDS; round++) {
66
- const res = await chatImpl(provider, messages, [...TOOLS], { timeoutMs: 120_000, retry: { attempts: 2 } });
67
- const calls = res.message.tool_calls ?? [];
68
- if (!calls.length)
69
- return res.message.content?.trim() || '(模型返回了空回复)';
200
+ const tools = extendedTools(deps);
201
+ step(`上下文就绪(工具 ${tools.length} 个,轮预算 ${maxRounds})`);
202
+ for (let round = 0; round < maxRounds; round++) {
203
+ // wall-clock bound (round 50): one REQUEST may not run forever — the
204
+ // sentinel + panel chaining carry the TASK onward, each segment visible
205
+ const outOfTime = Date.now() - t0 > wallClockMs;
206
+ // LAST round (or out of time): strip tools so the model MUST wrap up in
207
+ // prose — the user gets a real progress summary, not a code excuse
208
+ const last = round === maxRounds - 1 || outOfTime;
209
+ if (outOfTime)
210
+ step('已达单段时限,收尾汇报…');
211
+ step(`第 ${round + 1} 轮思考中…(已用 ${Math.round((Date.now() - t0) / 1000)}s)`);
212
+ const res = await chatImpl(provider, messages, last ? [] : [...tools], { timeoutMs: 120_000, retry: { attempts: 2 } });
213
+ const calls = last ? [] : res.message.tool_calls ?? [];
214
+ if (!calls.length) {
215
+ const text = res.message.content?.trim() || '(模型返回了空回复)';
216
+ // AUTONOMOUS CONTINUATION (round 49): the task is not done, the round
217
+ // budget is — the panel auto-sends 「继续」 when it sees this sentinel,
218
+ // so the user hands over a task and gets it finished, no babysitting
219
+ return last ? text + '\n[[hmh:auto-continue]]' : text;
220
+ }
221
+ step(`第 ${round + 1} 轮: ${calls.map((c) => c.function.name).join(', ')}`);
70
222
  messages.push(res.message);
71
223
  for (const call of calls) {
72
224
  let result;
73
225
  try {
74
226
  const args = JSON.parse(call.function.arguments || '{}');
75
- if (call.function.name === 'page_read') {
76
- result = JSON.stringify(await deps.readPage()).slice(0, 12_000);
77
- }
78
- else if (call.function.name === 'page_act') {
79
- deps.log?.(`侧栏对话触发页面操作: ${JSON.stringify(args)}`);
80
- result = JSON.stringify(await deps.act(args)).slice(0, 4_000);
227
+ if (pageFails >= 3 && (name => name === 'page_read' || name === 'page_act' || name === 'page_goto')(call.function.name)) {
228
+ result = JSON.stringify({ ok: false, error: '页面通道连续失败(扩展断连?)——已熔断。请停止页面操作:基于已有信息回答,或让用户重连扩展后重试。' });
81
229
  }
82
230
  else {
83
- result = JSON.stringify({ ok: false, error: `unknown tool ${call.function.name}` });
231
+ result = await dispatchTool(call.function.name, args, deps, origin, step);
232
+ if (/^page_/.test(call.function.name) && result.includes('"error"'))
233
+ pageFails++;
234
+ else if (/^page_/.test(call.function.name))
235
+ pageFails = 0;
84
236
  }
85
237
  }
86
238
  catch (err) {
87
239
  result = JSON.stringify({ ok: false, error: String(err instanceof Error ? err.message : err).slice(0, 200) });
240
+ if (/^page_/.test(call.function.name))
241
+ pageFails++;
88
242
  }
89
243
  messages.push({ role: 'tool', tool_call_id: call.id, content: result });
90
244
  }
91
245
  }
92
- return '(这一轮工具调用太多,已停下 — 请换个问法,或稍后再试)';
246
+ return '[[hmh:auto-continue]]';
247
+ }
248
+ async function dispatchTool(name, args, deps, origin, step) {
249
+ const json = (v, cap = 12_000) => JSON.stringify(v).slice(0, cap);
250
+ switch (name) {
251
+ case 'page_read': {
252
+ step?.('读取当前页面…');
253
+ try {
254
+ const r = await deps.readPage();
255
+ step?.('页面读取完成');
256
+ return json(r);
257
+ }
258
+ catch (e) {
259
+ step?.('页面读取失败: ' + String(e instanceof Error ? e.message : e).slice(0, 80));
260
+ throw e;
261
+ }
262
+ }
263
+ case 'page_act': {
264
+ step?.(`页面操作: ${String(args.action ?? '')} ${String(args.selector ?? args.direction ?? '').slice(0, 50)}`);
265
+ deps.log?.(`侧栏对话触发页面操作: ${JSON.stringify(args)}`);
266
+ return json(await deps.act(args), 4_000);
267
+ }
268
+ case 'page_goto': {
269
+ const url = String(args.url ?? '');
270
+ if (!/^https?:\/\//i.test(url))
271
+ return JSON.stringify({ ok: false, error: 'page_goto 只允许 http/https 地址' });
272
+ step?.(`导航: ${url.slice(0, 70)}`);
273
+ deps.log?.(`侧栏导航: ${url}`);
274
+ return json(await deps.goto(url), 2_000);
275
+ }
276
+ case 'tabs_list':
277
+ step?.('列出标签页…');
278
+ return json(await deps.listTabs(), 6_000);
279
+ case 'run_command': {
280
+ const command = String(args.command ?? '');
281
+ step?.(`命令待确认: ${command.slice(0, 80)}`);
282
+ // ALWAYS gated: turn N proposes (needConfirm) → user replies 「确认」 →
283
+ // turn N+1's pre-loop executes it and injects 【已执行】. A model
284
+ // re-calling the same command in one turn must NOT double-run it.
285
+ pendingConfirm.set(origin, {
286
+ kind: 'run_command',
287
+ summary: command,
288
+ run: () => deps.runCommand(command, Number(args.timeout_ms)),
289
+ });
290
+ return JSON.stringify({ needConfirm: true, message: `即将在终端执行: ${command}`, hint: '转达给用户:回复「确认」执行,回复其他内容取消。若上方已有【已执行】记录,不要重复执行,直接使用其结果。' });
291
+ }
292
+ case 'write_file': {
293
+ const path = String(args.path ?? '');
294
+ const content = String(args.content ?? '');
295
+ const summary = `write_file ${path}(${content.length} 字符)`;
296
+ pendingConfirm.set(origin, {
297
+ kind: 'write_file',
298
+ summary,
299
+ run: () => deps.writeFile(path, content),
300
+ });
301
+ return JSON.stringify({ needConfirm: true, message: `即将写入文件: ${summary}`, hint: '转达给用户:回复「确认」执行,回复其他内容取消。' });
302
+ }
303
+ case 'read_file':
304
+ step?.(`读取文件: ${String(args.path ?? '')}`);
305
+ return JSON.stringify(await deps.readFile(String(args.path ?? ''))).slice(0, 12_000);
306
+ case 'list_dir':
307
+ step?.(`列目录: ${String(args.path ?? '')}`);
308
+ return json(await deps.listDir(String(args.path ?? '')), 6_000);
309
+ default:
310
+ return JSON.stringify({ ok: false, error: `unknown tool ${name}` });
311
+ }
93
312
  }