mocode-ai 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.js +18 -7
- package/dist/agent/mentioned-files.js +71 -0
- package/dist/agent/model-turn.js +68 -30
- package/dist/agent/progress-guard.js +67 -0
- package/dist/agent/run-coordinator.js +155 -24
- package/dist/agent/short-path-completion.js +109 -0
- package/dist/agent/spawn.js +43 -0
- package/dist/agent/stages/history-manager.js +1 -0
- package/dist/agent/stages/tool-dispatcher.js +6 -3
- package/dist/agent/tool-helpers.js +2 -2
- package/dist/agent/tool-turn.js +49 -4
- package/dist/agent/work-discipline.js +12 -9
- package/dist/changeset/index.js +2 -1
- package/dist/config/index.js +12 -10
- package/dist/context/overlapping-reads.js +66 -0
- package/dist/context/relevance.js +11 -2
- package/dist/context/usage-snapshot.js +9 -6
- package/dist/host/stdio.js +96 -42
- package/dist/i18n/index.js +26 -10
- package/dist/llm/index.js +27 -3
- package/dist/llm/message-shape.js +18 -0
- package/dist/llm/reasoning.js +17 -0
- package/dist/memory/index.js +1 -1
- package/dist/memory/tail.js +9 -26
- 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/repl/commands/appearance.js +1 -2
- package/dist/repl/commands/compact.js +4 -0
- 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 +119 -77
- package/dist/rollback/index.js +2 -2
- package/dist/rollback/store.js +73 -38
- package/dist/runtime/runtime.js +1 -1
- package/dist/session/compact.js +41 -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/edit-file.js +79 -19
- package/dist/tools/builtins/grep.js +161 -42
- package/dist/tools/builtins/plan-update.js +4 -2
- package/dist/tools/builtins/read-file.js +148 -55
- package/dist/tools/builtins/run-command.js +57 -9
- package/dist/tools/ripgrep-client.js +72 -26
- 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/render.js +3 -0
- package/dist/ui/spinner.js +3 -1
- package/dist/verification/evidence.js +52 -0
- package/package.json +4 -2
package/dist/rollback/store.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, rmdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
3
|
-
import
|
|
2
|
+
import { chmodSync, existsSync, lstat, lstatSync, mkdirSync, readFile, readFileSync, readdir, readlinkSync, rmdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { readlink } from 'node:fs/promises';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
5
6
|
import { config } from '../config/index.js';
|
|
6
7
|
import { MAX_SNAPSHOT_TURNS } from '../tools/constants.js';
|
|
7
8
|
import { toText } from '../context/utils.js';
|
|
8
9
|
import { truncateDisplay } from '../ui/render.js';
|
|
9
|
-
const EXCLUDED_WORKSPACE_DIRS =
|
|
10
|
+
const EXCLUDED_WORKSPACE_DIRS = new Set([
|
|
10
11
|
'.git',
|
|
11
12
|
'.hg',
|
|
12
13
|
'.svn',
|
|
@@ -109,6 +110,10 @@ const SCAN_CONCURRENCY = 16;
|
|
|
109
110
|
const YIELD_EVERY = 64;
|
|
110
111
|
const YIELD_BYTES = 1024 * 1024;
|
|
111
112
|
const FRESH_WINDOW_MS = 2000;
|
|
113
|
+
// 扫描会发出数千次 I/O。用开销更低的 fs 回调实现,仍异步等待,避免阻塞界面。
|
|
114
|
+
const statEntry = promisify(lstat);
|
|
115
|
+
const listDirectory = promisify(readdir);
|
|
116
|
+
const readEntry = promisify(readFile);
|
|
112
117
|
/**
|
|
113
118
|
* contentCache 的常驻字节上限(base64 后的长度和);0 = 不限。
|
|
114
119
|
*
|
|
@@ -208,7 +213,7 @@ export class RollbackStore {
|
|
|
208
213
|
const full = path.resolve(root, rel);
|
|
209
214
|
return full !== root && this.isInside(root, full) ? full : null;
|
|
210
215
|
}
|
|
211
|
-
readState(full) {
|
|
216
|
+
readState(full, preparedFile) {
|
|
212
217
|
try {
|
|
213
218
|
const stat = lstatSync(full);
|
|
214
219
|
const mode = stat.mode & 0o777;
|
|
@@ -217,7 +222,7 @@ export class RollbackStore {
|
|
|
217
222
|
if (stat.isDirectory())
|
|
218
223
|
return { kind: 'directory', mode };
|
|
219
224
|
if (stat.isFile())
|
|
220
|
-
return { kind: 'file', data: readFileSync(full).toString('base64'), mode };
|
|
225
|
+
return { kind: 'file', data: (preparedFile ?? readFileSync(full)).toString('base64'), mode };
|
|
221
226
|
}
|
|
222
227
|
catch {
|
|
223
228
|
// 不存在或不可读均按 missing;工具若最终也不可读,不会产生伪变化。
|
|
@@ -317,12 +322,12 @@ export class RollbackStore {
|
|
|
317
322
|
getCurrentTurnId() {
|
|
318
323
|
return this.currentTurnId;
|
|
319
324
|
}
|
|
320
|
-
beginPathMutation(value) {
|
|
325
|
+
beginPathMutation(value, preparedFile) {
|
|
321
326
|
const workspaceRoot = this.rootDir();
|
|
322
327
|
const full = path.resolve(workspaceRoot, value);
|
|
323
328
|
return {
|
|
324
329
|
path: this.toRel(workspaceRoot, full),
|
|
325
|
-
before: this.readState(full),
|
|
330
|
+
before: this.readState(full, preparedFile),
|
|
326
331
|
sequence: ++this.sequenceCounter,
|
|
327
332
|
createdParents: this.missingParents(workspaceRoot, full),
|
|
328
333
|
turnId: this.currentTurnId,
|
|
@@ -352,55 +357,69 @@ export class RollbackStore {
|
|
|
352
357
|
if (changed)
|
|
353
358
|
this.mutationVersion += 1;
|
|
354
359
|
}
|
|
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
360
|
async scanWorkspace(workspaceRoot, sessionsRoot) {
|
|
362
361
|
const entries = new Map();
|
|
363
362
|
const nextCache = new Map();
|
|
364
363
|
const paths = [];
|
|
364
|
+
if (this.isInside(sessionsRoot, workspaceRoot)) {
|
|
365
|
+
this.contentCache.clear();
|
|
366
|
+
return entries;
|
|
367
|
+
}
|
|
368
|
+
const prefix = workspaceRoot.endsWith(path.sep) ? workspaceRoot : workspaceRoot + path.sep;
|
|
369
|
+
const sessionName = path.basename(sessionsRoot).toLowerCase();
|
|
370
|
+
const excluded = (name, rel) => {
|
|
371
|
+
const lower = name.toLowerCase();
|
|
372
|
+
return (EXCLUDED_WORKSPACE_DIRS.has(lower) ||
|
|
373
|
+
(lower === sessionName && path.relative(sessionsRoot, prefix + rel) === ''));
|
|
374
|
+
};
|
|
375
|
+
const readDir = (rel) => listDirectory(prefix + rel, { withFileTypes: true }).catch(() => []);
|
|
376
|
+
// 仅读取本次扫描的目录。预取兄弟目录,仍按原来的深度优先顺序消费,保留条目上限的语义。
|
|
377
|
+
const ahead = new Map();
|
|
365
378
|
const walk = async (dir) => {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
379
|
+
const listing = ahead.get(dir) ?? readDir(dir);
|
|
380
|
+
ahead.delete(dir);
|
|
381
|
+
const children = await listing;
|
|
382
|
+
const parent = dir ? dir + path.sep : '';
|
|
383
|
+
for (const child of children) {
|
|
384
|
+
if (ahead.size >= SCAN_CONCURRENCY)
|
|
385
|
+
break;
|
|
386
|
+
if (!child.isDirectory())
|
|
387
|
+
continue;
|
|
388
|
+
const rel = parent + child.name;
|
|
389
|
+
if (!excluded(child.name, rel))
|
|
390
|
+
ahead.set(rel, readDir(rel));
|
|
374
391
|
}
|
|
375
392
|
for (const child of children) {
|
|
376
393
|
if (paths.length >= CAPTURE_ENTRY_LIMIT)
|
|
377
394
|
return;
|
|
378
|
-
const
|
|
379
|
-
if (
|
|
395
|
+
const rel = parent + child.name;
|
|
396
|
+
if (excluded(child.name, rel))
|
|
380
397
|
continue;
|
|
381
|
-
paths.push(
|
|
382
|
-
if (child.isDirectory())
|
|
383
|
-
|
|
398
|
+
paths.push(rel);
|
|
399
|
+
if (child.isDirectory() && paths.length < CAPTURE_ENTRY_LIMIT) {
|
|
400
|
+
startWorkers();
|
|
401
|
+
await walk(rel);
|
|
402
|
+
}
|
|
384
403
|
}
|
|
385
404
|
};
|
|
386
|
-
await walk(workspaceRoot);
|
|
387
405
|
let budget = CAPTURE_TOTAL_LIMIT;
|
|
388
406
|
let cursor = 0;
|
|
389
407
|
let processed = 0;
|
|
390
408
|
let bytesSinceYield = 0;
|
|
391
409
|
const worker = async () => {
|
|
392
410
|
while (cursor < paths.length) {
|
|
393
|
-
const
|
|
411
|
+
const rel = paths[cursor++];
|
|
412
|
+
const full = prefix + rel;
|
|
394
413
|
if (++processed % YIELD_EVERY === 0 || bytesSinceYield >= YIELD_BYTES) {
|
|
395
414
|
bytesSinceYield = 0;
|
|
396
415
|
await this.yieldToEventLoop();
|
|
397
416
|
}
|
|
398
417
|
let state;
|
|
399
418
|
try {
|
|
400
|
-
const stat = await
|
|
419
|
+
const stat = await statEntry(full, { bigint: true });
|
|
401
420
|
const mode = Number(stat.mode) & 0o777;
|
|
402
421
|
if (stat.isSymbolicLink()) {
|
|
403
|
-
const target = await
|
|
422
|
+
const target = await readlink(full);
|
|
404
423
|
state = { kind: 'symlink', data: target, stamp: target, mode };
|
|
405
424
|
}
|
|
406
425
|
else if (stat.isDirectory()) {
|
|
@@ -419,7 +438,7 @@ export class RollbackStore {
|
|
|
419
438
|
else if (size <= CAPTURE_FILE_LIMIT && budget - size >= 0) {
|
|
420
439
|
budget -= size;
|
|
421
440
|
bytesSinceYield += size;
|
|
422
|
-
const data =
|
|
441
|
+
const data = await readEntry(full, 'base64');
|
|
423
442
|
state = { kind: 'file', data, stamp, mode };
|
|
424
443
|
nextCache.set(full, { stamp, mode, data });
|
|
425
444
|
}
|
|
@@ -435,10 +454,21 @@ export class RollbackStore {
|
|
|
435
454
|
state = { kind: 'missing' };
|
|
436
455
|
}
|
|
437
456
|
if (state.kind !== 'missing')
|
|
438
|
-
entries.set(
|
|
457
|
+
entries.set(rel, state);
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
// 深度优先枚举仍决定条目上限,同时让已发现的路径与后续目录读取并行。
|
|
461
|
+
const workers = new Set();
|
|
462
|
+
const startWorkers = () => {
|
|
463
|
+
const count = Math.min(SCAN_CONCURRENCY - workers.size, paths.length - cursor);
|
|
464
|
+
for (let i = 0; i < count; i++) {
|
|
465
|
+
const pending = worker().finally(() => workers.delete(pending));
|
|
466
|
+
workers.add(pending);
|
|
439
467
|
}
|
|
440
468
|
};
|
|
441
|
-
await
|
|
469
|
+
await walk('');
|
|
470
|
+
startWorkers();
|
|
471
|
+
await Promise.all(workers);
|
|
442
472
|
this.contentCache = trimContentCache(nextCache);
|
|
443
473
|
return entries;
|
|
444
474
|
}
|
|
@@ -458,15 +488,20 @@ export class RollbackStore {
|
|
|
458
488
|
}
|
|
459
489
|
async endWorkspaceMutation(capture, op) {
|
|
460
490
|
const after = await this.scanWorkspace(capture.workspaceRoot, capture.sessionsRoot);
|
|
461
|
-
const
|
|
491
|
+
const missing = { kind: 'missing' };
|
|
462
492
|
let changed = false;
|
|
463
|
-
|
|
464
|
-
const beforeState = capture.entries.get(rel) ?? { kind: 'missing' };
|
|
465
|
-
const afterState = after.get(rel) ?? { kind: 'missing' };
|
|
493
|
+
const recordChange = (rel, beforeState, afterState) => {
|
|
466
494
|
if (this.sameState(beforeState, afterState))
|
|
467
|
-
|
|
495
|
+
return;
|
|
468
496
|
changed = true;
|
|
469
497
|
this.addSnapshot(this.snapshotFromState(capture.turnId, rel, beforeState, capture.sequence, op, [], afterState));
|
|
498
|
+
};
|
|
499
|
+
for (const [rel, beforeState] of capture.entries) {
|
|
500
|
+
recordChange(rel, beforeState, after.get(rel) ?? missing);
|
|
501
|
+
}
|
|
502
|
+
for (const [rel, afterState] of after) {
|
|
503
|
+
if (!capture.entries.has(rel))
|
|
504
|
+
recordChange(rel, missing, afterState);
|
|
470
505
|
}
|
|
471
506
|
if (changed)
|
|
472
507
|
this.mutationVersion += 1;
|
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);
|
|
@@ -950,7 +987,7 @@ export async function compactHistory(history, opts) {
|
|
|
950
987
|
// 随后被覆盖——落盘 compacted/seg-NNN.md,模型事后靠 grep/read_file 回捞精确原文。
|
|
951
988
|
// best-effort:失败只丢回捞能力,绝不阻塞压缩。
|
|
952
989
|
let archivedPath = null;
|
|
953
|
-
if (state
|
|
990
|
+
if (state.archiveHistory) {
|
|
954
991
|
try {
|
|
955
992
|
archivedPath = getActiveSessionStore().archiveCompactedMessages(getCurrentSessionId() ?? '', older);
|
|
956
993
|
}
|
|
@@ -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')));
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/** 只读探索工具:重复执行相同调用视为纯浪费。 */
|
|
2
|
+
export const READ_ONLY_TOOLS = new Set(['read_file', 'grep', 'glob']);
|
|
3
|
+
function finiteNumber(value) {
|
|
4
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
|
5
|
+
}
|
|
6
|
+
export function reduceShortPathEfficiency(events) {
|
|
7
|
+
let toolCalls = 0;
|
|
8
|
+
let mutationCalls = 0;
|
|
9
|
+
let readOnlyCalls = 0;
|
|
10
|
+
let modelRequests = 0;
|
|
11
|
+
let firstEditSeen = false;
|
|
12
|
+
let requestsBeforeFirstEdit = null;
|
|
13
|
+
let readCallsBeforeFirstEdit = null;
|
|
14
|
+
let postEditReadOnlyCalls = 0;
|
|
15
|
+
let repeatedIdentical = 0;
|
|
16
|
+
const seenReadOnly = new Map();
|
|
17
|
+
let promptTokens = 0;
|
|
18
|
+
let completionTokens = 0;
|
|
19
|
+
let cachedTokens = 0;
|
|
20
|
+
let totalTokens = 0;
|
|
21
|
+
let hasTokens = false;
|
|
22
|
+
let hasCached = false;
|
|
23
|
+
let durationMs = 0;
|
|
24
|
+
const phases = {
|
|
25
|
+
routeDurationMs: null,
|
|
26
|
+
modelAttempts: 0,
|
|
27
|
+
modelDurationMs: 0,
|
|
28
|
+
uncachedPromptTokens: null,
|
|
29
|
+
postEditCommands: 0,
|
|
30
|
+
postEditCommandDurationMs: 0,
|
|
31
|
+
finalModelRequests: 0,
|
|
32
|
+
finalModelDurationMs: 0,
|
|
33
|
+
completion: null,
|
|
34
|
+
fallbackReason: null,
|
|
35
|
+
};
|
|
36
|
+
let uncachedPromptTokens = 0;
|
|
37
|
+
let requestsWithCacheUsage = 0;
|
|
38
|
+
const modelDurations = new Map();
|
|
39
|
+
const firstEdit = {
|
|
40
|
+
firstAttemptApplied: null,
|
|
41
|
+
requests: null,
|
|
42
|
+
toolOutputTokensEstimate: null,
|
|
43
|
+
uncachedInputTokens: null,
|
|
44
|
+
};
|
|
45
|
+
let firstEditCall;
|
|
46
|
+
let exploredToolTokens = 0;
|
|
47
|
+
let completeToolEstimates = true;
|
|
48
|
+
for (const event of events) {
|
|
49
|
+
if (event.type === 'tool_route') {
|
|
50
|
+
phases.routeDurationMs = finiteNumber(event.data.latencyMs);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (event.type === 'short_path_completion') {
|
|
54
|
+
phases.completion = event.data.status === 'completed' ? 'automatic' : 'fallback';
|
|
55
|
+
phases.fallbackReason = typeof event.data.reason === 'string' ? event.data.reason : null;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (event.type === 'model_retry') {
|
|
59
|
+
phases.modelAttempts += 1;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (event.type === 'model_end') {
|
|
63
|
+
phases.modelAttempts += 1;
|
|
64
|
+
// 同一步的 overflow 重试复用起始时钟,取最大累计耗时。
|
|
65
|
+
const step = event.step ?? event.eventId;
|
|
66
|
+
const elapsed = finiteNumber(event.data.durationMs) ?? 0;
|
|
67
|
+
modelDurations.set(step, Math.max(elapsed, modelDurations.get(step) ?? 0));
|
|
68
|
+
if (String(event.data.status ?? '') !== 'success')
|
|
69
|
+
continue;
|
|
70
|
+
modelRequests += 1;
|
|
71
|
+
if (toolCalls > 0) {
|
|
72
|
+
phases.finalModelRequests += 1;
|
|
73
|
+
phases.finalModelDurationMs += elapsed;
|
|
74
|
+
}
|
|
75
|
+
const prompt = finiteNumber(event.data.promptTokens);
|
|
76
|
+
const completion = finiteNumber(event.data.completionTokens);
|
|
77
|
+
const total = finiteNumber(event.data.totalTokens);
|
|
78
|
+
if (prompt !== null || completion !== null || total !== null) {
|
|
79
|
+
hasTokens = true;
|
|
80
|
+
promptTokens += prompt ?? 0;
|
|
81
|
+
completionTokens += completion ?? 0;
|
|
82
|
+
totalTokens += total ?? (prompt ?? 0) + (completion ?? 0);
|
|
83
|
+
}
|
|
84
|
+
const cached = finiteNumber(event.data.cachedTokens);
|
|
85
|
+
if (cached !== null) {
|
|
86
|
+
hasCached = true;
|
|
87
|
+
cachedTokens += cached;
|
|
88
|
+
if (prompt !== null && cached <= prompt) {
|
|
89
|
+
requestsWithCacheUsage += 1;
|
|
90
|
+
uncachedPromptTokens += prompt - cached;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (event.type === 'tool_call_start') {
|
|
96
|
+
toolCalls += 1;
|
|
97
|
+
phases.finalModelRequests = 0;
|
|
98
|
+
phases.finalModelDurationMs = 0;
|
|
99
|
+
const tool = typeof event.data.tool === 'string' ? event.data.tool : '';
|
|
100
|
+
if ((tool === 'edit_file' || tool === 'write_file') && !firstEditCall)
|
|
101
|
+
firstEditCall = event;
|
|
102
|
+
if (!READ_ONLY_TOOLS.has(tool))
|
|
103
|
+
continue;
|
|
104
|
+
readOnlyCalls += 1;
|
|
105
|
+
if (firstEditSeen)
|
|
106
|
+
postEditReadOnlyCalls += 1;
|
|
107
|
+
const fingerprint = typeof event.data.argumentHash === 'string' ? event.data.argumentHash : '';
|
|
108
|
+
const key = `${tool}:${fingerprint}`;
|
|
109
|
+
const seen = seenReadOnly.get(key) ?? 0;
|
|
110
|
+
if (seen > 0)
|
|
111
|
+
repeatedIdentical += 1;
|
|
112
|
+
seenReadOnly.set(key, seen + 1);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (event.type === 'tool_call_end') {
|
|
116
|
+
if (firstEditSeen && event.data.tool === 'run_command') {
|
|
117
|
+
phases.postEditCommands += 1;
|
|
118
|
+
phases.postEditCommandDurationMs += finiteNumber(event.data.durationMs) ?? 0;
|
|
119
|
+
}
|
|
120
|
+
const changedFiles = event.data.changedFiles;
|
|
121
|
+
const changed = Array.isArray(changedFiles) && changedFiles.length > 0;
|
|
122
|
+
const tool = event.data.tool;
|
|
123
|
+
const isEdit = tool === 'edit_file' || tool === 'write_file';
|
|
124
|
+
const applied = event.data.status === 'success' && changed;
|
|
125
|
+
if (isEdit &&
|
|
126
|
+
firstEdit.firstAttemptApplied === null &&
|
|
127
|
+
(!firstEditCall ||
|
|
128
|
+
(firstEditCall.toolCallId ? firstEditCall.toolCallId === event.toolCallId : firstEditCall.data.tool === tool))) {
|
|
129
|
+
firstEdit.firstAttemptApplied = applied;
|
|
130
|
+
}
|
|
131
|
+
if (firstEdit.requests === null) {
|
|
132
|
+
if (isEdit && applied) {
|
|
133
|
+
firstEdit.requests = modelRequests;
|
|
134
|
+
firstEdit.toolOutputTokensEstimate = completeToolEstimates ? exploredToolTokens : null;
|
|
135
|
+
firstEdit.uncachedInputTokens =
|
|
136
|
+
modelRequests > 0 && requestsWithCacheUsage === modelRequests ? uncachedPromptTokens : null;
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
const outputTokens = finiteNumber(event.data.outputTokensEstimate);
|
|
140
|
+
if (outputTokens === null)
|
|
141
|
+
completeToolEstimates = false;
|
|
142
|
+
else
|
|
143
|
+
exploredToolTokens += outputTokens;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (!changed)
|
|
147
|
+
continue;
|
|
148
|
+
mutationCalls += 1;
|
|
149
|
+
if (!firstEditSeen) {
|
|
150
|
+
firstEditSeen = true;
|
|
151
|
+
requestsBeforeFirstEdit = modelRequests;
|
|
152
|
+
readCallsBeforeFirstEdit = readOnlyCalls;
|
|
153
|
+
}
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (event.type === 'turn_end') {
|
|
157
|
+
durationMs = finiteNumber(event.data.durationMs) ?? durationMs;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
phases.modelDurationMs = [...modelDurations.values()].reduce((total, ms) => total + ms, 0);
|
|
161
|
+
if (modelRequests > 0 && requestsWithCacheUsage === modelRequests) {
|
|
162
|
+
phases.uncachedPromptTokens = uncachedPromptTokens;
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
toolCalls,
|
|
166
|
+
mutationCalls,
|
|
167
|
+
readOnlyCalls,
|
|
168
|
+
modelRequests,
|
|
169
|
+
requestsBeforeFirstEdit,
|
|
170
|
+
readCallsBeforeFirstEdit,
|
|
171
|
+
repeatedIdenticalReadOnlyCalls: repeatedIdentical,
|
|
172
|
+
postEditReadOnlyCalls,
|
|
173
|
+
promptTokens: hasTokens ? promptTokens : null,
|
|
174
|
+
completionTokens: hasTokens ? completionTokens : null,
|
|
175
|
+
cachedTokens: hasCached ? cachedTokens : null,
|
|
176
|
+
totalTokens: hasTokens ? totalTokens : null,
|
|
177
|
+
durationMs,
|
|
178
|
+
firstEdit,
|
|
179
|
+
phases,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** 任意一段 trace(如 warm 预热轮)里的只读调用数,用于判断预热轮是否真的建立了上下文。 */
|
|
183
|
+
export function countReadOnlyCalls(events) {
|
|
184
|
+
return events.filter((event) => event.type === 'tool_call_start' && READ_ONLY_TOOLS.has(String(event.data.tool ?? ''))).length;
|
|
185
|
+
}
|
package/dist/session/store.js
CHANGED
|
@@ -5,6 +5,7 @@ import { gzipSync } from 'node:zlib';
|
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { MAX_TRACE_BYTES, MAX_TRACE_ROTATIONS, MAX_COMPACTED_ARCHIVE_BYTES } from '../tools/constants.js';
|
|
7
7
|
import { loadArchivedSession, readArchiveIndex, retentionPaths } from './retention.js';
|
|
8
|
+
import { parseTerminalTranscript, readTerminalTranscriptFile, writeTerminalTranscriptFile, } from './terminal-transcript.js';
|
|
8
9
|
import { COMPACTED_DIRNAME, isCompactedAssetName, parseSegmentMeta, renderArchiveIndex, renderCompactedSegment, resultBlobFileName, RESULT_BLOB_FILE_RE, SEGMENT_FILE_RE, } from './compact-archive.js';
|
|
9
10
|
import { config, getActiveModel } from '../config/index.js';
|
|
10
11
|
import { getWorkspaceRoot } from '../workspace/index.js';
|
|
@@ -24,11 +25,42 @@ function idToIso(id) {
|
|
|
24
25
|
return id;
|
|
25
26
|
return `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}${m[7] ? `.${m[7]}` : ''}`;
|
|
26
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* 一条 user 消息的 content → 一行人读文本。
|
|
30
|
+
*
|
|
31
|
+
* 多模态 content(文字 + 图片)**不能**直接 JSON.stringify:那会把
|
|
32
|
+
* `[{"type":"text","text":"这是?"},{"type":"image_url","image_url":{…}}]` 整段塞进
|
|
33
|
+
* firstUser,会话列表里就显示成一串 JSON(实测仓库里 13 条会话如此,侧栏读到的是
|
|
34
|
+
* 截到 40 字符的半截 JSON,既不是人话也解析不了)。图片按 `[图片]` 占位 ——
|
|
35
|
+
* 标题要的是「我第一句说了什么」,不是 base64。
|
|
36
|
+
*/
|
|
27
37
|
function toText(content) {
|
|
28
38
|
if (content == null)
|
|
29
39
|
return '';
|
|
30
40
|
if (typeof content === 'string')
|
|
31
41
|
return content;
|
|
42
|
+
if (Array.isArray(content)) {
|
|
43
|
+
const texts = [];
|
|
44
|
+
let hasImage = false;
|
|
45
|
+
for (const part of content) {
|
|
46
|
+
if (typeof part === 'string') {
|
|
47
|
+
texts.push(part);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (!part || typeof part !== 'object')
|
|
51
|
+
continue;
|
|
52
|
+
const piece = part;
|
|
53
|
+
if (piece.type === 'text' && typeof piece.text === 'string')
|
|
54
|
+
texts.push(piece.text);
|
|
55
|
+
else if (piece.type === 'image_url')
|
|
56
|
+
hasImage = true;
|
|
57
|
+
}
|
|
58
|
+
const joined = texts.join(' ').trim();
|
|
59
|
+
if (joined)
|
|
60
|
+
return joined;
|
|
61
|
+
if (hasImage)
|
|
62
|
+
return '[图片]';
|
|
63
|
+
}
|
|
32
64
|
try {
|
|
33
65
|
return JSON.stringify(content);
|
|
34
66
|
}
|
|
@@ -43,10 +75,44 @@ function firstUserOf(history) {
|
|
|
43
75
|
const text = toText(message.content)
|
|
44
76
|
.replace(/\n/g, ' ')
|
|
45
77
|
.trim();
|
|
78
|
+
if (!text)
|
|
79
|
+
continue;
|
|
46
80
|
return truncateDisplay(text, 40);
|
|
47
81
|
}
|
|
48
82
|
return '';
|
|
49
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* 读侧修正老的 firstUser:早期版本把多模态 content 直接 JSON.stringify 存进了这个字段,
|
|
86
|
+
* 于是一批会话在列表里永远显示成 `[{"type":"text","text":"这是?"},…]`(落盘值不会自愈,
|
|
87
|
+
* 只有该会话下次 save 才会重算)。以 `[` / `{` 开头即视为序列化产物,改从 history 重算;
|
|
88
|
+
* history 不可用时退回原值。
|
|
89
|
+
*
|
|
90
|
+
* 用户真的把一段 JSON 当第一句话粘贴时也安全:content 是字符串,重算结果与落盘值逐字相同。
|
|
91
|
+
*/
|
|
92
|
+
function repairFirstUser(record) {
|
|
93
|
+
const stored = typeof record.firstUser === 'string' ? record.firstUser : '';
|
|
94
|
+
const head = stored.trimStart()[0];
|
|
95
|
+
if (head !== '[' && head !== '{')
|
|
96
|
+
return stored;
|
|
97
|
+
if (!Array.isArray(record.history))
|
|
98
|
+
return stored;
|
|
99
|
+
return firstUserOf(record.history) || stored;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* 归档会话的 firstUser 修正:归档条目只有索引里的标题,内联 history 在 `archive/<id>.json.gz`。
|
|
103
|
+
*
|
|
104
|
+
* 只为「看起来是序列化产物」的条目解一次 gz —— 每个工作空间这类条目通常 0~1 条,
|
|
105
|
+
* 不值得为它给整个列表加一次全量解压。
|
|
106
|
+
*/
|
|
107
|
+
function repairArchivedFirstUser(sessionsRoot, id, stored) {
|
|
108
|
+
const head = stored.trimStart()[0];
|
|
109
|
+
if (head !== '[' && head !== '{')
|
|
110
|
+
return stored;
|
|
111
|
+
const archived = loadArchivedSession(sessionsRoot, id);
|
|
112
|
+
if (!archived || !Array.isArray(archived.history))
|
|
113
|
+
return stored;
|
|
114
|
+
return firstUserOf(archived.history) || stored;
|
|
115
|
+
}
|
|
50
116
|
/** compacted/ 总量上限:MOCODE_MAX_COMPACTED_BYTES 覆盖(供测试/小盘),非法值回退默认。 */
|
|
51
117
|
function envMaxCompactedBytes() {
|
|
52
118
|
const raw = process.env.MOCODE_MAX_COMPACTED_BYTES;
|
|
@@ -486,6 +552,15 @@ export class SessionStore {
|
|
|
486
552
|
}
|
|
487
553
|
}
|
|
488
554
|
}
|
|
555
|
+
loadTerminalTranscript(id) {
|
|
556
|
+
return (readTerminalTranscriptFile(path.join(this.sessionsRoot, id)) ??
|
|
557
|
+
parseTerminalTranscript(loadArchivedSession(this.sessionsRoot, id)?.terminalTranscript));
|
|
558
|
+
}
|
|
559
|
+
saveTerminalTranscript(id, transcript) {
|
|
560
|
+
const dir = path.join(this.sessionsRoot, id);
|
|
561
|
+
this.ensureDir(dir);
|
|
562
|
+
writeTerminalTranscriptFile(dir, transcript);
|
|
563
|
+
}
|
|
489
564
|
load(id, opts) {
|
|
490
565
|
const currentPath = this.sessionPath(id);
|
|
491
566
|
const legacyPath = path.join(this.sessionsRoot, `${id}.json`);
|
|
@@ -509,7 +584,7 @@ export class SessionStore {
|
|
|
509
584
|
id: rec.id,
|
|
510
585
|
createdAt: rec.createdAt ?? idToIso(rec.id ?? id),
|
|
511
586
|
model: rec.model ?? '',
|
|
512
|
-
firstUser: rec
|
|
587
|
+
firstUser: repairFirstUser(rec),
|
|
513
588
|
history: rec.history,
|
|
514
589
|
queryHistory: Array.isArray(rec.queryHistory)
|
|
515
590
|
? rec.queryHistory.filter((query) => typeof query === 'string')
|
|
@@ -632,7 +707,7 @@ export class SessionStore {
|
|
|
632
707
|
id: rec.id,
|
|
633
708
|
createdAt: rec.createdAt ?? idToIso(rec.id),
|
|
634
709
|
model: rec.model ?? '',
|
|
635
|
-
firstUser: rec
|
|
710
|
+
firstUser: repairFirstUser(rec),
|
|
636
711
|
});
|
|
637
712
|
}
|
|
638
713
|
catch {
|
|
@@ -649,7 +724,7 @@ export class SessionStore {
|
|
|
649
724
|
id: e.id,
|
|
650
725
|
createdAt: e.createdAt ?? idToIso(e.id),
|
|
651
726
|
model: e.model ?? '',
|
|
652
|
-
firstUser: e.firstUser ?? '',
|
|
727
|
+
firstUser: repairArchivedFirstUser(root, e.id, e.firstUser ?? ''),
|
|
653
728
|
archived: true,
|
|
654
729
|
});
|
|
655
730
|
}
|