mocode-ai 1.9.9 → 1.10.1
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/agent/index.js +13 -3
- package/dist/agent/mentioned-files.js +71 -0
- package/dist/agent/model-turn.js +83 -16
- package/dist/agent/progress-guard.js +67 -0
- package/dist/agent/run-coordinator.js +151 -23
- package/dist/agent/short-path-completion.js +109 -0
- package/dist/agent/spawn.js +46 -0
- package/dist/agent/stages/history-manager.js +1 -0
- package/dist/agent/tool-helpers.js +2 -2
- package/dist/agent/tool-turn.js +49 -4
- package/dist/agent/work-discipline.js +9 -9
- package/dist/changeset/unified-diff.js +59 -0
- package/dist/config/index.js +13 -10
- package/dist/context/relevance.js +2 -1
- package/dist/context/usage-snapshot.js +50 -0
- package/dist/headless.js +3 -1
- package/dist/host/commit-message.js +41 -0
- package/dist/host/protocol.js +205 -10
- package/dist/host/stdio.js +1096 -63
- package/dist/i18n/index.js +26 -10
- package/dist/llm/index.js +28 -3
- package/dist/llm/message-shape.js +45 -0
- package/dist/llm/providers/anthropic.js +2 -0
- package/dist/llm/reasoning.js +17 -0
- package/dist/memory/adoption.js +159 -27
- package/dist/memory/anchor-relocate.js +227 -0
- package/dist/memory/consolidate-skips.js +196 -0
- package/dist/memory/health.js +88 -6
- package/dist/memory/index.js +2 -1
- package/dist/memory/reflect.js +36 -4
- package/dist/memory/store.js +30 -0
- package/dist/models/reasoning-cap.js +19 -2
- package/dist/orchestrator/lane-executor.js +7 -1
- package/dist/orchestrator/repl.js +30 -49
- package/dist/prompt/system-prompt.js +30 -0
- package/dist/repl/commands/appearance.js +1 -2
- package/dist/repl/commands/compact.js +4 -0
- package/dist/repl/commands/diff.js +5 -46
- package/dist/repl/commands/memory.js +77 -4
- package/dist/repl/commands/model-actions.js +4 -3
- package/dist/repl/commands/model.js +2 -3
- package/dist/repl/message-format.js +7 -6
- package/dist/repl/running-input.js +27 -65
- package/dist/repl/runtime.js +129 -89
- package/dist/repl/status-bar.js +4 -38
- package/dist/rollback/store.js +36 -23
- package/dist/runtime/browser-diagnostics.js +77 -0
- package/dist/runtime/browser-manager.js +150 -22
- package/dist/runtime/runtime.js +1 -1
- package/dist/session/compact.js +44 -4
- package/dist/session/retention.js +4 -0
- package/dist/session/short-path-metrics.js +185 -0
- package/dist/session/store.js +78 -3
- package/dist/session/terminal-transcript.js +101 -0
- package/dist/tools/builtins/ask-human.js +2 -2
- package/dist/tools/builtins/browser.js +4 -1
- package/dist/tools/builtins/edit-file.js +28 -5
- package/dist/tools/builtins/grep.js +85 -35
- package/dist/tools/builtins/memory-save.js +1 -1
- package/dist/tools/builtins/memory-update.js +1 -1
- package/dist/tools/builtins/plan-update.js +4 -2
- package/dist/tools/builtins/read-file.js +95 -44
- package/dist/tools/builtins/run-command.js +57 -9
- package/dist/tools/builtins/task.js +4 -0
- package/dist/tools/constants.js +8 -0
- package/dist/tools/ripgrep-client.js +31 -11
- package/dist/tools/tool-runtime.js +29 -8
- package/dist/ui/layout-internal/content-write.js +7 -3
- package/dist/ui/layout-internal/core.js +1 -1
- package/dist/ui/layout-internal/state.js +0 -6
- package/dist/ui/layout-internal/statusbar.js +0 -30
- package/dist/ui/output-sink.js +24 -0
- package/dist/ui/spinner.js +3 -1
- package/package.json +4 -2
package/dist/rollback/store.js
CHANGED
|
@@ -6,7 +6,7 @@ import { config } from '../config/index.js';
|
|
|
6
6
|
import { MAX_SNAPSHOT_TURNS } from '../tools/constants.js';
|
|
7
7
|
import { toText } from '../context/utils.js';
|
|
8
8
|
import { truncateDisplay } from '../ui/render.js';
|
|
9
|
-
const EXCLUDED_WORKSPACE_DIRS =
|
|
9
|
+
const EXCLUDED_WORKSPACE_DIRS = new Set([
|
|
10
10
|
'.git',
|
|
11
11
|
'.hg',
|
|
12
12
|
'.svn',
|
|
@@ -352,45 +352,58 @@ export class RollbackStore {
|
|
|
352
352
|
if (changed)
|
|
353
353
|
this.mutationVersion += 1;
|
|
354
354
|
}
|
|
355
|
-
isWorkspaceExcluded(full, sessionsRoot) {
|
|
356
|
-
const base = path.basename(full).toLowerCase();
|
|
357
|
-
if (EXCLUDED_WORKSPACE_DIRS.includes(base))
|
|
358
|
-
return true;
|
|
359
|
-
return this.isInside(sessionsRoot, full);
|
|
360
|
-
}
|
|
361
355
|
async scanWorkspace(workspaceRoot, sessionsRoot) {
|
|
362
356
|
const entries = new Map();
|
|
363
357
|
const nextCache = new Map();
|
|
364
358
|
const paths = [];
|
|
359
|
+
if (this.isInside(sessionsRoot, workspaceRoot)) {
|
|
360
|
+
this.contentCache.clear();
|
|
361
|
+
return entries;
|
|
362
|
+
}
|
|
363
|
+
const prefix = workspaceRoot.endsWith(path.sep) ? workspaceRoot : workspaceRoot + path.sep;
|
|
364
|
+
const sessionName = path.basename(sessionsRoot).toLowerCase();
|
|
365
|
+
const excluded = (name, rel) => {
|
|
366
|
+
const lower = name.toLowerCase();
|
|
367
|
+
return (EXCLUDED_WORKSPACE_DIRS.has(lower) ||
|
|
368
|
+
(lower === sessionName && path.relative(sessionsRoot, prefix + rel) === ''));
|
|
369
|
+
};
|
|
370
|
+
const readDir = (rel) => fsp.readdir(prefix + rel, { withFileTypes: true }).catch(() => []);
|
|
371
|
+
// 仅读取本次扫描的目录。预取兄弟目录,仍按原来的深度优先顺序消费,保留条目上限的语义。
|
|
372
|
+
const ahead = new Map();
|
|
365
373
|
const walk = async (dir) => {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
+
const listing = ahead.get(dir) ?? readDir(dir);
|
|
375
|
+
ahead.delete(dir);
|
|
376
|
+
const children = await listing;
|
|
377
|
+
const parent = dir ? dir + path.sep : '';
|
|
378
|
+
for (const child of children) {
|
|
379
|
+
if (ahead.size >= SCAN_CONCURRENCY)
|
|
380
|
+
break;
|
|
381
|
+
if (!child.isDirectory())
|
|
382
|
+
continue;
|
|
383
|
+
const rel = parent + child.name;
|
|
384
|
+
if (!excluded(child.name, rel))
|
|
385
|
+
ahead.set(rel, readDir(rel));
|
|
374
386
|
}
|
|
375
387
|
for (const child of children) {
|
|
376
388
|
if (paths.length >= CAPTURE_ENTRY_LIMIT)
|
|
377
389
|
return;
|
|
378
|
-
const
|
|
379
|
-
if (
|
|
390
|
+
const rel = parent + child.name;
|
|
391
|
+
if (excluded(child.name, rel))
|
|
380
392
|
continue;
|
|
381
|
-
paths.push(
|
|
382
|
-
if (child.isDirectory())
|
|
383
|
-
await walk(
|
|
393
|
+
paths.push(rel);
|
|
394
|
+
if (child.isDirectory() && paths.length < CAPTURE_ENTRY_LIMIT)
|
|
395
|
+
await walk(rel);
|
|
384
396
|
}
|
|
385
397
|
};
|
|
386
|
-
await walk(
|
|
398
|
+
await walk('');
|
|
387
399
|
let budget = CAPTURE_TOTAL_LIMIT;
|
|
388
400
|
let cursor = 0;
|
|
389
401
|
let processed = 0;
|
|
390
402
|
let bytesSinceYield = 0;
|
|
391
403
|
const worker = async () => {
|
|
392
404
|
while (cursor < paths.length) {
|
|
393
|
-
const
|
|
405
|
+
const rel = paths[cursor++];
|
|
406
|
+
const full = prefix + rel;
|
|
394
407
|
if (++processed % YIELD_EVERY === 0 || bytesSinceYield >= YIELD_BYTES) {
|
|
395
408
|
bytesSinceYield = 0;
|
|
396
409
|
await this.yieldToEventLoop();
|
|
@@ -435,7 +448,7 @@ export class RollbackStore {
|
|
|
435
448
|
state = { kind: 'missing' };
|
|
436
449
|
}
|
|
437
450
|
if (state.kind !== 'missing')
|
|
438
|
-
entries.set(
|
|
451
|
+
entries.set(rel, state);
|
|
439
452
|
}
|
|
440
453
|
};
|
|
441
454
|
await Promise.all(Array.from({ length: Math.min(SCAN_CONCURRENCY, Math.max(1, paths.length)) }, worker));
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// 浏览器会话诊断的采集与落盘。
|
|
2
|
+
//
|
|
3
|
+
// 设计要点(对齐 Chrome DevTools MCP 的 Token-Optimized / Reference-over-Value):
|
|
4
|
+
// - 工具结果只回「计数 + 尾部若干行 + 日志路径」,绝不回吐全量控制台;
|
|
5
|
+
// 细节由模型自己 grep / read_file 日志文件按需取。
|
|
6
|
+
// - 计数与环缓冲分开维护:环缓冲会丢弃最老的条目,但计数必须是累计值,
|
|
7
|
+
// 否则「有多少条报错」会随缓冲滑动而变小,模型据此会误判问题已消失。
|
|
8
|
+
// - 日志写入串行排队(同一文件,不能交错),并设体积上限防止长会话撑爆磁盘。
|
|
9
|
+
import { appendFile, mkdir } from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
export const DEFAULT_RING_LIMIT = 200;
|
|
12
|
+
export const DEFAULT_TAIL_SIZE = 10;
|
|
13
|
+
export const DEFAULT_MAX_LOG_BYTES = 2 * 1024 * 1024;
|
|
14
|
+
/** 会话日志落点:`<root>/.mocode/browser/<sessionId>.log`。 */
|
|
15
|
+
export function resolveDiagnosticsLogPath(root, sessionId) {
|
|
16
|
+
return path.join(root, '.mocode', 'browser', `${sessionId}.log`);
|
|
17
|
+
}
|
|
18
|
+
export function createDiagnostics(options = {}) {
|
|
19
|
+
const state = {
|
|
20
|
+
counts: { console: 0, pageErrors: 0, failedRequests: 0 },
|
|
21
|
+
ring: { console: [], pageErrors: [], failedRequests: [] },
|
|
22
|
+
log: options.logPath ? { path: options.logPath, bytes: 0, truncated: false, queue: Promise.resolve() } : null,
|
|
23
|
+
limits: {
|
|
24
|
+
ring: options.ringLimit ?? DEFAULT_RING_LIMIT,
|
|
25
|
+
tail: options.tailSize ?? DEFAULT_TAIL_SIZE,
|
|
26
|
+
maxLogBytes: options.maxLogBytes ?? DEFAULT_MAX_LOG_BYTES,
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
// 目录创建失败只需降级为纯内存,不该让浏览器能力整体不可用。
|
|
30
|
+
if (state.log) {
|
|
31
|
+
const sink = state.log;
|
|
32
|
+
sink.queue = mkdir(path.dirname(sink.path), { recursive: true }).then(() => undefined, () => {
|
|
33
|
+
state.log = null;
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return state;
|
|
37
|
+
}
|
|
38
|
+
export function recordDiagnostic(state, bucket, line) {
|
|
39
|
+
state.counts[bucket] += 1;
|
|
40
|
+
const target = state.ring[bucket];
|
|
41
|
+
target.push(line);
|
|
42
|
+
if (target.length > state.limits.ring)
|
|
43
|
+
target.splice(0, target.length - state.limits.ring);
|
|
44
|
+
const sink = state.log;
|
|
45
|
+
if (!sink || sink.truncated)
|
|
46
|
+
return;
|
|
47
|
+
const text = `[${bucket}] ${line}\n`;
|
|
48
|
+
sink.bytes += Buffer.byteLength(text);
|
|
49
|
+
if (sink.bytes > state.limits.maxLogBytes) {
|
|
50
|
+
sink.truncated = true;
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
// 串行追加:并发事件各自接在上一次写入之后,避免同一文件内容交错。
|
|
54
|
+
sink.queue = sink.queue
|
|
55
|
+
.then(() => appendFile(sink.path, text))
|
|
56
|
+
.catch(() => {
|
|
57
|
+
/* 日志是增强能力,写失败不影响采集 */
|
|
58
|
+
})
|
|
59
|
+
.then(() => undefined);
|
|
60
|
+
}
|
|
61
|
+
export function snapshotDiagnostics(state) {
|
|
62
|
+
const cut = (items) => items.slice(-state.limits.tail);
|
|
63
|
+
return {
|
|
64
|
+
counts: { ...state.counts },
|
|
65
|
+
tail: {
|
|
66
|
+
console: cut(state.ring.console),
|
|
67
|
+
pageErrors: cut(state.ring.pageErrors),
|
|
68
|
+
failedRequests: cut(state.ring.failedRequests),
|
|
69
|
+
},
|
|
70
|
+
...(state.log ? { logPath: state.log.path } : {}),
|
|
71
|
+
...(state.log?.truncated ? { logTruncated: true } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** 等待排队中的日志写入落盘(测试与收尾时用)。 */
|
|
75
|
+
export async function flushDiagnostics(state) {
|
|
76
|
+
await state.log?.queue.catch(() => { });
|
|
77
|
+
}
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
// - 采集 console / pageerror / requestfailed 到有界 ring buffer:前端问题往往只在控制台可见,
|
|
11
11
|
// 截图看不出来。
|
|
12
12
|
import { randomBytes } from 'node:crypto';
|
|
13
|
+
import { getSandboxRoot } from '../sandbox/root.js';
|
|
14
|
+
import { createDiagnostics, recordDiagnostic, resolveDiagnosticsLogPath, snapshotDiagnostics, } from './browser-diagnostics.js';
|
|
13
15
|
export class BrowserManagerError extends Error {
|
|
14
16
|
code;
|
|
15
17
|
constructor(code, message) {
|
|
@@ -18,13 +20,17 @@ export class BrowserManagerError extends Error {
|
|
|
18
20
|
this.name = 'BrowserManagerError';
|
|
19
21
|
}
|
|
20
22
|
}
|
|
23
|
+
const ATTACHED_SESSION_ID = 'panel';
|
|
21
24
|
const sessions = new Map();
|
|
22
|
-
const DIAGNOSTIC_LIMIT = 200;
|
|
23
25
|
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
24
26
|
const MAX_TIMEOUT_MS = 60_000;
|
|
25
27
|
const DEFAULT_VIEWPORT = { width: 1280, height: 800 };
|
|
28
|
+
/** 面板页可能还没导航完;attach 时轮询等待它出现。 */
|
|
29
|
+
const ATTACH_WAIT_ATTEMPTS = 15;
|
|
30
|
+
const ATTACH_WAIT_INTERVAL_MS = 200;
|
|
26
31
|
let browserPromise = null;
|
|
27
32
|
let launchedHeaded = false;
|
|
33
|
+
let attachPromise = null;
|
|
28
34
|
function errorMessage(error) {
|
|
29
35
|
return error instanceof Error ? error.message : String(error);
|
|
30
36
|
}
|
|
@@ -113,32 +119,141 @@ async function getBrowser(headed) {
|
|
|
113
119
|
}
|
|
114
120
|
}
|
|
115
121
|
function record(session, bucket, line) {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
122
|
+
recordDiagnostic(session.diag, bucket, line);
|
|
123
|
+
}
|
|
124
|
+
/** 诊断日志落在工作区的 `.mocode/browser/` 下,模型可用 grep/read_file 按需取细节。 */
|
|
125
|
+
function openDiagnostics(sessionId) {
|
|
126
|
+
const root = getSandboxRoot() ?? process.cwd();
|
|
127
|
+
try {
|
|
128
|
+
return createDiagnostics({ logPath: resolveDiagnosticsLogPath(root, sessionId) });
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
// 只读工作区等场景建不了目录:降级成纯内存诊断,不影响浏览器功能。
|
|
132
|
+
return createDiagnostics({ logPath: null });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** CDP 端点:由宿主应用(workspace 的浏览器面板)在启动时注入;CLI 下不存在。 */
|
|
136
|
+
export function attachedEndpoint() {
|
|
137
|
+
const value = (process.env.MOCODE_BROWSER_CDP_URL ?? '').trim();
|
|
138
|
+
return value ? value : null;
|
|
139
|
+
}
|
|
140
|
+
function bindPageListeners(session) {
|
|
141
|
+
const { page } = session;
|
|
142
|
+
const onConsole = (message) => {
|
|
143
|
+
record(session, 'console', `[${message.type()}] ${message.text()}`);
|
|
144
|
+
};
|
|
145
|
+
const onPageError = (error) => record(session, 'pageErrors', errorMessage(error));
|
|
146
|
+
const onRequestFailed = (request) => {
|
|
147
|
+
record(session, 'failedRequests', `${request.method()} ${request.url()} — ${request.failure()?.errorText ?? 'failed'}`);
|
|
148
|
+
};
|
|
149
|
+
page.on('console', onConsole);
|
|
150
|
+
page.on('pageerror', onPageError);
|
|
151
|
+
page.on('requestfailed', onRequestFailed);
|
|
152
|
+
const offConsole = () => {
|
|
153
|
+
page.off('console', onConsole);
|
|
154
|
+
};
|
|
155
|
+
const offPageError = () => {
|
|
156
|
+
page.off('pageerror', onPageError);
|
|
157
|
+
};
|
|
158
|
+
const offRequestFailed = () => {
|
|
159
|
+
page.off('requestfailed', onRequestFailed);
|
|
160
|
+
};
|
|
161
|
+
session.cleanup = [offConsole, offPageError, offRequestFailed];
|
|
162
|
+
}
|
|
163
|
+
function createSessionRecord(input) {
|
|
164
|
+
const session = {
|
|
165
|
+
...input,
|
|
166
|
+
diag: openDiagnostics(input.sessionId),
|
|
167
|
+
cleanup: [],
|
|
168
|
+
};
|
|
169
|
+
input.page.setDefaultTimeout(DEFAULT_TIMEOUT_MS);
|
|
170
|
+
bindPageListeners(session);
|
|
171
|
+
return session;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* 宿主应用浏览器面板的空白页哨兵。面板初始停在 `about:blank#mocode-browser-panel`:
|
|
175
|
+
* 它既能让 attach 拿到「一块属于面板的页面」,又不会让模型误以为用户已经打开了某个站点。
|
|
176
|
+
* 应用自身的 renderer 是 file://,永远不会命中这里。
|
|
177
|
+
* (对应实现在 packages/work-app/src/browser-host.ts 的 PANEL_BLANK_URL,改动需同步。)
|
|
178
|
+
*/
|
|
179
|
+
const PANEL_SENTINEL = '#mocode-browser-panel';
|
|
180
|
+
/**
|
|
181
|
+
* 接管宿主应用面板里的页面(`connectOverCDP`)。
|
|
182
|
+
*
|
|
183
|
+
* 关键点:面板的网页必须是 CDP 里的 `page` 目标 —— `<webview>` 是 `webview` 目标,
|
|
184
|
+
* playwright 根本不会把它放进 BrowserContext,所以宿主一律用 WebContentsView 承载面板。
|
|
185
|
+
* 这里按优先级挑:先 http(s)(用户真正在看的站点),再面板哨兵空白页。
|
|
186
|
+
*/
|
|
187
|
+
async function openAttachedSession(endpoint) {
|
|
188
|
+
const existing = sessions.get(ATTACHED_SESSION_ID);
|
|
189
|
+
if (existing && !existing.page.isClosed())
|
|
190
|
+
return describe(existing);
|
|
191
|
+
const playwright = await loadDriver();
|
|
192
|
+
if (!attachPromise) {
|
|
193
|
+
attachPromise = playwright.chromium.connectOverCDP(endpoint);
|
|
194
|
+
}
|
|
195
|
+
let browser;
|
|
196
|
+
try {
|
|
197
|
+
browser = await attachPromise;
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
attachPromise = null;
|
|
201
|
+
throw new BrowserManagerError('EXECUTION_ERROR', `Unable to attach to the app browser panel at ${endpoint} (${errorMessage(error)}). ` +
|
|
202
|
+
'Open the browser panel in the app first, or unset MOCODE_BROWSER_CDP_URL.');
|
|
203
|
+
}
|
|
204
|
+
const wanted = process.env.MOCODE_BROWSER_PANEL_MATCH ?? '';
|
|
205
|
+
let picked = null;
|
|
206
|
+
for (let attempt = 0; attempt < ATTACH_WAIT_ATTEMPTS && !picked; attempt++) {
|
|
207
|
+
// 两轮:先找用户真正打开的站点,再退到面板哨兵空白页 —— 后者保证「用户刚打开面板、
|
|
208
|
+
// 还没输网址」时 agent 也能先拿到这块页面,navigate 下去就是同一个视图。
|
|
209
|
+
for (const pass of ['site', 'blank']) {
|
|
210
|
+
for (const context of browser.contexts()) {
|
|
211
|
+
const page = context.pages().find((candidate) => {
|
|
212
|
+
const url = candidate.url();
|
|
213
|
+
if (pass === 'blank')
|
|
214
|
+
return url.includes(PANEL_SENTINEL);
|
|
215
|
+
if (!url.startsWith('http:') && !url.startsWith('https:'))
|
|
216
|
+
return false;
|
|
217
|
+
return wanted ? url.includes(wanted) : true;
|
|
218
|
+
});
|
|
219
|
+
if (page) {
|
|
220
|
+
picked = { context, page };
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (picked)
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
if (!picked)
|
|
228
|
+
await new Promise((resolve) => setTimeout(resolve, ATTACH_WAIT_INTERVAL_MS));
|
|
229
|
+
}
|
|
230
|
+
if (!picked) {
|
|
231
|
+
throw new BrowserManagerError('EXECUTION_ERROR', 'The app browser panel has no page open yet. Open the Browser view in the app and retry.');
|
|
232
|
+
}
|
|
233
|
+
const session = createSessionRecord({
|
|
234
|
+
sessionId: ATTACHED_SESSION_ID,
|
|
235
|
+
context: picked.context,
|
|
236
|
+
page: picked.page,
|
|
237
|
+
headed: true,
|
|
238
|
+
attached: true,
|
|
239
|
+
});
|
|
240
|
+
sessions.set(ATTACHED_SESSION_ID, session);
|
|
241
|
+
return describe(session);
|
|
120
242
|
}
|
|
121
243
|
export async function openSession(opts = {}) {
|
|
244
|
+
const endpoint = attachedEndpoint();
|
|
245
|
+
if (endpoint)
|
|
246
|
+
return openAttachedSession(endpoint);
|
|
122
247
|
const headed = opts.headed === true;
|
|
123
248
|
const browser = await getBrowser(headed);
|
|
124
249
|
const context = await browser.newContext({ viewport: DEFAULT_VIEWPORT });
|
|
125
250
|
const page = await context.newPage();
|
|
126
|
-
|
|
127
|
-
const session = {
|
|
251
|
+
const session = createSessionRecord({
|
|
128
252
|
sessionId: `page-${randomBytes(3).toString('hex')}`,
|
|
129
253
|
context,
|
|
130
254
|
page,
|
|
131
255
|
headed,
|
|
132
|
-
|
|
133
|
-
pageErrors: [],
|
|
134
|
-
failedRequests: [],
|
|
135
|
-
};
|
|
136
|
-
page.on('console', (message) => {
|
|
137
|
-
record(session, 'console', `[${message.type()}] ${message.text()}`);
|
|
138
|
-
});
|
|
139
|
-
page.on('pageerror', (error) => record(session, 'pageErrors', errorMessage(error)));
|
|
140
|
-
page.on('requestfailed', (request) => {
|
|
141
|
-
record(session, 'failedRequests', `${request.method()} ${request.url()} — ${request.failure()?.errorText ?? 'failed'}`);
|
|
256
|
+
attached: false,
|
|
142
257
|
});
|
|
143
258
|
sessions.set(session.sessionId, session);
|
|
144
259
|
return describe(session);
|
|
@@ -171,6 +286,7 @@ function describe(session) {
|
|
|
171
286
|
title: '',
|
|
172
287
|
headed: session.headed,
|
|
173
288
|
viewport,
|
|
289
|
+
...(session.attached ? { attached: true } : {}),
|
|
174
290
|
};
|
|
175
291
|
}
|
|
176
292
|
async function describeAsync(session) {
|
|
@@ -188,11 +304,7 @@ function wrapActionError(error) {
|
|
|
188
304
|
throw new BrowserManagerError('EXECUTION_ERROR', message);
|
|
189
305
|
}
|
|
190
306
|
function diagnostics(session) {
|
|
191
|
-
return
|
|
192
|
-
console: session.console.slice(-20),
|
|
193
|
-
pageErrors: session.pageErrors.slice(-20),
|
|
194
|
-
failedRequests: session.failedRequests.slice(-20),
|
|
195
|
-
};
|
|
307
|
+
return snapshotDiagnostics(session.diag);
|
|
196
308
|
}
|
|
197
309
|
async function finish(session, action) {
|
|
198
310
|
return { action, ...(await describeAsync(session)), diagnostics: diagnostics(session) };
|
|
@@ -296,6 +408,12 @@ export function listSessions() {
|
|
|
296
408
|
export async function closeSession(sessionId) {
|
|
297
409
|
const session = requireSession(sessionId);
|
|
298
410
|
sessions.delete(session.sessionId);
|
|
411
|
+
for (const off of session.cleanup)
|
|
412
|
+
off();
|
|
413
|
+
if (session.attached) {
|
|
414
|
+
// 面板里的页面属于用户:只解绑监听,绝不关闭 context/浏览器。
|
|
415
|
+
return { sessionId: session.sessionId, closed: true };
|
|
416
|
+
}
|
|
299
417
|
await session.context.close().catch(() => { });
|
|
300
418
|
if (sessions.size === 0 && browserPromise) {
|
|
301
419
|
const browser = await browserPromise.catch(() => null);
|
|
@@ -308,6 +426,11 @@ export async function closeSession(sessionId) {
|
|
|
308
426
|
export async function closeAllBrowsers() {
|
|
309
427
|
for (const session of [...sessions.values()]) {
|
|
310
428
|
sessions.delete(session.sessionId);
|
|
429
|
+
for (const off of session.cleanup)
|
|
430
|
+
off();
|
|
431
|
+
// attach 的页面不归我们所有,只解绑;否则关一次会话就把用户的面板页关了。
|
|
432
|
+
if (session.attached)
|
|
433
|
+
continue;
|
|
311
434
|
await session.context.close().catch(() => { });
|
|
312
435
|
}
|
|
313
436
|
const pending = browserPromise;
|
|
@@ -316,4 +439,9 @@ export async function closeAllBrowsers() {
|
|
|
316
439
|
return;
|
|
317
440
|
const browser = await pending.catch(() => null);
|
|
318
441
|
await browser?.close().catch(() => { });
|
|
442
|
+
// CDP 连接是「连到别人的浏览器」,断开即可,不 close。
|
|
443
|
+
const attached = attachPromise;
|
|
444
|
+
attachPromise = null;
|
|
445
|
+
const remote = await attached?.catch(() => null);
|
|
446
|
+
await remote?.close().catch(() => { });
|
|
319
447
|
}
|
package/dist/runtime/runtime.js
CHANGED
|
@@ -42,7 +42,7 @@ export class Runtime {
|
|
|
42
42
|
constructor(init = {}) {
|
|
43
43
|
const { context, contextState, onStart, onClose, ...contextInit } = init;
|
|
44
44
|
this.context = context ?? createAgentRuntimeContext(contextInit);
|
|
45
|
-
this.contextState = contextState ?? createContextState();
|
|
45
|
+
this.contextState = contextState ?? createContextState({ archiveHistory: true });
|
|
46
46
|
this.onStart = onStart;
|
|
47
47
|
this.onClose = onClose;
|
|
48
48
|
this.session = {
|
package/dist/session/compact.js
CHANGED
|
@@ -23,10 +23,15 @@ export const defaultCompactionRuntime = {
|
|
|
23
23
|
modelTransport: chat,
|
|
24
24
|
rollbackStore: defaultRollbackStore,
|
|
25
25
|
};
|
|
26
|
-
export function createContextState() {
|
|
27
|
-
return {
|
|
26
|
+
export function createContextState(options = {}) {
|
|
27
|
+
return {
|
|
28
|
+
lastEstimate: 0,
|
|
29
|
+
correction: 1,
|
|
30
|
+
calibrationSamples: 0,
|
|
31
|
+
...(options.archiveHistory ? { archiveHistory: true } : {}),
|
|
32
|
+
};
|
|
28
33
|
}
|
|
29
|
-
export const contextState = createContextState();
|
|
34
|
+
export const contextState = createContextState({ archiveHistory: true });
|
|
30
35
|
/** 中截:text 太长时保 head + 标记 + tail,总长 ≤ max。 */
|
|
31
36
|
export function truncateMid(text, max) {
|
|
32
37
|
if (text.length <= max)
|
|
@@ -719,8 +724,40 @@ function compactionLogLine(label, before, after, window) {
|
|
|
719
724
|
/**
|
|
720
725
|
* 压缩 history(原地)。手动 /compact 与自动 maybeCompact 都走这里。
|
|
721
726
|
* 不检查阈值——调用方(maybeCompact)决定是否调;/compact 直接调以强制压缩。
|
|
727
|
+
*
|
|
728
|
+
* 这一层只做「进度广播 + 异常收口」:真正的压缩逻辑在 compactHistoryInner。
|
|
729
|
+
* done 事件在三类出口都发——成功/兜底返回、摘要抛错(failed)、abort(aborted)——
|
|
730
|
+
* 否则 GUI 的「正在压缩」状态行会在异常路径上永久挂着。
|
|
722
731
|
*/
|
|
723
732
|
export async function compactHistory(history, opts) {
|
|
733
|
+
const notify = opts.runtime?.onCompactProgress;
|
|
734
|
+
if (!notify)
|
|
735
|
+
return compactHistoryInner(history, opts);
|
|
736
|
+
const manual = opts.manual === true;
|
|
737
|
+
const force = opts.force === true;
|
|
738
|
+
notify({ phase: 'start', manual, force, ...(opts.focus ? { focus: opts.focus } : {}) });
|
|
739
|
+
try {
|
|
740
|
+
const result = await compactHistoryInner(history, opts);
|
|
741
|
+
notify({
|
|
742
|
+
phase: 'done',
|
|
743
|
+
manual,
|
|
744
|
+
compacted: result.compacted,
|
|
745
|
+
summarized: result.summarized,
|
|
746
|
+
reason: result.reason,
|
|
747
|
+
estimateBefore: result.estimateBefore,
|
|
748
|
+
estimateAfter: result.estimateAfter,
|
|
749
|
+
historyRebuilt: result.historyRebuilt === true,
|
|
750
|
+
});
|
|
751
|
+
return result;
|
|
752
|
+
}
|
|
753
|
+
catch (cause) {
|
|
754
|
+
const aborted = opts.signal?.aborted === true ||
|
|
755
|
+
(cause instanceof Error && (cause.name === 'AbortError' || cause.name === 'APIUserAbortError'));
|
|
756
|
+
notify({ phase: 'done', manual, compacted: false, summarized: false, failed: true, aborted });
|
|
757
|
+
throw cause;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
async function compactHistoryInner(history, opts) {
|
|
724
761
|
const state = opts.contextState ?? contextState;
|
|
725
762
|
const activeTools = opts.tools ?? chatTools;
|
|
726
763
|
const estimateBefore = rawPromptTokens(history, activeTools);
|
|
@@ -848,6 +885,7 @@ export async function compactHistory(history, opts) {
|
|
|
848
885
|
const estimateAfter = rawPromptTokens(history, activeTools);
|
|
849
886
|
state.lastEstimate = estimatePromptTokens(history, activeTools, state.correction);
|
|
850
887
|
state.lastUsage = undefined;
|
|
888
|
+
state.promptAnchor = undefined; // 单组微压缩后,旧实测锚点也不能继续外推。
|
|
851
889
|
if (!layout.isLastContentRowBlank())
|
|
852
890
|
layout.contentWrite('\n');
|
|
853
891
|
layout.contentWrite(compactionLogLine('强制微压缩(单组)', estimateBefore, estimateAfter, opts.window));
|
|
@@ -949,7 +987,7 @@ export async function compactHistory(history, opts) {
|
|
|
949
987
|
// 随后被覆盖——落盘 compacted/seg-NNN.md,模型事后靠 grep/read_file 回捞精确原文。
|
|
950
988
|
// best-effort:失败只丢回捞能力,绝不阻塞压缩。
|
|
951
989
|
let archivedPath = null;
|
|
952
|
-
if (state
|
|
990
|
+
if (state.archiveHistory) {
|
|
953
991
|
try {
|
|
954
992
|
archivedPath = getActiveSessionStore().archiveCompactedMessages(getCurrentSessionId() ?? '', older);
|
|
955
993
|
}
|
|
@@ -974,6 +1012,7 @@ export async function compactHistory(history, opts) {
|
|
|
974
1012
|
const estimateAfter = rawPromptTokens(history, activeTools);
|
|
975
1013
|
state.lastEstimate = estimatePromptTokens(history, activeTools, state.correction);
|
|
976
1014
|
state.lastUsage = undefined; // 压缩后旧 usage 失效,/context 改用估算
|
|
1015
|
+
state.promptAnchor = undefined; // 摘要/保留区已替换,不能沿用压缩前请求的实测基线。
|
|
977
1016
|
// 压缩行与上一个工具批次摘要行之间补空行分隔(compact 在 core step 循环顶部触发,
|
|
978
1017
|
// 上一步的 batch 可能尚未 flush,缓冲末行仍是 ● 工具摘要行 → 两行黏在一起)。
|
|
979
1018
|
if (!layout.isLastContentRowBlank())
|
|
@@ -1005,6 +1044,7 @@ export async function compactHistory(history, opts) {
|
|
|
1005
1044
|
const estimateAfter = rawPromptTokens(history, activeTools);
|
|
1006
1045
|
state.lastEstimate = estimatePromptTokens(history, activeTools, state.correction);
|
|
1007
1046
|
state.lastUsage = undefined; // token 数已变,旧 usage 失效
|
|
1047
|
+
state.promptAnchor = undefined; // 原地微压缩可能保持消息数不变,必须按内容失效。
|
|
1008
1048
|
if (microcompactDone) {
|
|
1009
1049
|
if (!layout.isLastContentRowBlank())
|
|
1010
1050
|
layout.contentWrite('\n');
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
13
13
|
import path from 'node:path';
|
|
14
14
|
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
15
|
+
import { readTerminalTranscriptFile } from './terminal-transcript.js';
|
|
15
16
|
import { COMPACTED_DIRNAME, isCompactedAssetName } from './compact-archive.js';
|
|
16
17
|
import { TextSearchIndex } from '../context/text-search.js';
|
|
17
18
|
import { config } from '../config/index.js';
|
|
@@ -211,6 +212,9 @@ function archiveSession(sessionsRoot, id, now) {
|
|
|
211
212
|
const assets = readCompactedAssets(sessionsRoot, id);
|
|
212
213
|
if (Object.keys(assets).length > 0)
|
|
213
214
|
record.compactedAssets = assets;
|
|
215
|
+
const terminalTranscript = readTerminalTranscriptFile(dir);
|
|
216
|
+
if (terminalTranscript)
|
|
217
|
+
record.terminalTranscript = terminalTranscript;
|
|
214
218
|
mkdirSync(paths.archiveDir, { recursive: true });
|
|
215
219
|
const gzPath = path.join(paths.archiveDir, `${id}.json.gz`);
|
|
216
220
|
writeFileSync(gzPath + '.tmp', gzipSync(Buffer.from(JSON.stringify(record), 'utf8')));
|