mocode-ai 1.9.2 → 1.9.4
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/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/dist/agent/model-turn.js +27 -1
- package/dist/context/budget.js +19 -81
- package/dist/context/index.js +1 -1
- package/dist/i18n/index.js +58 -18
- package/dist/repl/commands/compact.js +1 -1
- package/dist/repl/commands/stats.js +94 -61
- package/dist/repl/commands.js +8 -1
- package/dist/repl/runtime.js +3 -0
- package/dist/repl/status-bar.js +35 -12
- package/dist/session/backfill-usage.js +154 -0
- package/dist/session/global-usage.js +20 -7
- package/dist/session/index.js +2 -2
- package/dist/session/notes.js +12 -2
- package/dist/session/scheduler.js +29 -3
- package/dist/session/usage-chart.js +113 -0
- package/dist/session/usage-stats.js +3 -1
- package/dist/ui/layout-internal/core.js +34 -2
- package/dist/ui/layout-internal/input-paint.js +14 -12
- package/dist/ui/layout-internal/state.js +16 -3
- package/dist/ui/layout-internal/statusbar.js +203 -25
- package/dist/ui/layout-types.js +1 -0
- package/dist/workspace/index.js +2 -0
- package/dist/workspace/registry.js +145 -0
- package/package.json +1 -1
package/dist/repl/status-bar.js
CHANGED
|
@@ -13,7 +13,7 @@ import { formatArtifactTokenSources } from '../context/artifacts.js';
|
|
|
13
13
|
import { getAgentMode } from '../agent/mode.js';
|
|
14
14
|
import { getCurrentSessionId } from '../session/state.js';
|
|
15
15
|
import { getSandboxRoot } from '../sandbox/root.js';
|
|
16
|
-
import { planStepLabel } from '../session/notes.js';
|
|
16
|
+
import { planStepLabel, planStepParts } from '../session/notes.js';
|
|
17
17
|
/** /context 的用量条(详情版,进内容区):只算对话内容(不含 system prompt),方便用户感知自己发了多少、agent 回复了多少。 */
|
|
18
18
|
export function renderContextBar(history) {
|
|
19
19
|
// 过滤掉 system 消息,只算对话内容
|
|
@@ -56,7 +56,7 @@ export function renderContextBar(history) {
|
|
|
56
56
|
* 空对话(只有 system 提示、还没发任何消息)恒显 0% 0/window:固定 system prompt + 工具
|
|
57
57
|
* schema 是每次请求的基础设施开销,不算用户占用的上下文,避免刚进 REPL 就显示十几 k。
|
|
58
58
|
* 有对话后必须**用全 prompt 估算**(消息 + 工具 schema + 尾部 ephemeral 注入),与压缩触发器
|
|
59
|
-
* evaluateBudget 的
|
|
59
|
+
* evaluateBudget 的 total / rawTotal 总账对齐——任何一段漏算都会让
|
|
60
60
|
* bar 与触发器口径不一致、看着没到 80% 实际已经在压。
|
|
61
61
|
* 触发器用 `Math.max(rawTotal, total) >= 0.8 * window`,bar 也照搬:校正后和校正前
|
|
62
62
|
* 哪个大取哪个,确保不会因 correction<1 而低估。ephemeral 文本由 agent/core 每步写入
|
|
@@ -132,20 +132,40 @@ export function readPlanStatusFromNotes() {
|
|
|
132
132
|
return null;
|
|
133
133
|
const endOffset = lines.slice(start + 1).findIndex((line) => /^##\s/.test(line));
|
|
134
134
|
const end = endOffset < 0 ? lines.length : start + 1 + endOffset;
|
|
135
|
-
const
|
|
135
|
+
const sectionLines = lines.slice(start + 1, end);
|
|
136
|
+
const section = [lines[start], ...sectionLines].join('\n').trimEnd();
|
|
136
137
|
const title = lines[start].match(/^## Plan:\s*(.+)$/)?.[1].trim();
|
|
137
138
|
if (!title)
|
|
138
139
|
return null;
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
140
|
+
const stepRe = /^\s*-\s*\[([ xX])\]\s*(\d+)\.\s*(.*)$/;
|
|
141
|
+
let total = 0;
|
|
142
|
+
let currentMatch = null;
|
|
143
|
+
const steps = [];
|
|
144
|
+
for (const line of sectionLines) {
|
|
145
|
+
const m = line.match(stepRe);
|
|
146
|
+
if (!m)
|
|
147
|
+
continue;
|
|
148
|
+
total++;
|
|
149
|
+
const done = m[1].toLowerCase() === 'x';
|
|
150
|
+
const isCurrent = !done && currentMatch === null;
|
|
151
|
+
if (isCurrent)
|
|
152
|
+
currentMatch = m;
|
|
153
|
+
steps.push({
|
|
154
|
+
no: Number(m[2]),
|
|
155
|
+
label: planStepLabel(m[3] ?? ''),
|
|
156
|
+
detail: planStepParts(m[3] ?? '').detail || undefined,
|
|
157
|
+
done,
|
|
158
|
+
current: isCurrent,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
const current = currentMatch ? planStepLabel(currentMatch[3] ?? '') : undefined;
|
|
142
162
|
// 括号进度 = 「当前执行到的步骤序号/总数」(执行第 1 步显示 1/3),与 `▸ 当前步` 后缀自洽;
|
|
143
163
|
// 旧语义 done/total 会永远慢一拍(执行第 2 步显示 1/3)。全勾选时显示 total/total(通常已自动结算为 Done,chip 消失)。
|
|
144
|
-
const activeNo = currentMatch ? Number(currentMatch[
|
|
164
|
+
const activeNo = currentMatch ? Number(currentMatch[2]) : total;
|
|
145
165
|
const summary = `plan: ${title} (${activeNo}/${total})`;
|
|
146
166
|
// mtime 让“相同内容被重写为一项新计划”也能重新出现,而不被旧轮次误抑制。
|
|
147
167
|
const fingerprint = `${sessionId}\0${fs.statSync(p).mtimeMs}\0${section}`;
|
|
148
|
-
return { fingerprint, summary: current ? `${summary} ▸ ${current}` : summary };
|
|
168
|
+
return { fingerprint, title, steps, summary: current ? `${summary} ▸ ${current}` : summary };
|
|
149
169
|
}
|
|
150
170
|
catch {
|
|
151
171
|
return null;
|
|
@@ -155,22 +175,25 @@ export function readPlanStatusFromNotes() {
|
|
|
155
175
|
export function settlePlanStatus() {
|
|
156
176
|
settledPlanFingerprint = readPlanStatusFromNotes()?.fingerprint;
|
|
157
177
|
}
|
|
158
|
-
/** 从 notes.md 读取活跃 plan
|
|
178
|
+
/** 从 notes.md 读取活跃 plan;已结算且未变化的旧 plan 返回 null(状态栏不显示)。 */
|
|
159
179
|
export function readPlanFromNotes() {
|
|
160
180
|
const plan = readPlanStatusFromNotes();
|
|
161
181
|
if (!plan || plan.fingerprint === settledPlanFingerprint)
|
|
162
|
-
return
|
|
163
|
-
return plan.summary;
|
|
182
|
+
return null;
|
|
183
|
+
return { summary: plan.summary, key: plan.title, steps: plan.steps };
|
|
164
184
|
}
|
|
165
185
|
/** 状态行基线:模型 / context / cwd / 模式标识 / 活跃 plan chip / 本轮 token。repl 在轮次边界、切模式、plan 变更时调。 */
|
|
166
186
|
export function refreshStatusBase(history, lastTurnUsage) {
|
|
187
|
+
const plan = readPlanFromNotes();
|
|
167
188
|
layout.setStatusBase({
|
|
168
189
|
model: config.model,
|
|
169
190
|
contextBar: renderContextBarInline(history),
|
|
170
191
|
cwd: process.cwd(),
|
|
171
192
|
modeTag: getAgentMode() === 'plan' ? 'Plan' : 'Auto',
|
|
172
193
|
effort: getActiveEffort() === 'auto' ? undefined : getActiveEffort(),
|
|
173
|
-
planSummary:
|
|
194
|
+
planSummary: plan?.summary ?? '',
|
|
195
|
+
planKey: plan?.key,
|
|
196
|
+
planSteps: plan?.steps,
|
|
174
197
|
lastTurnUsage,
|
|
175
198
|
});
|
|
176
199
|
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 历史 token 用量回填。
|
|
3
|
+
*
|
|
4
|
+
* 全局账本(~/.mocode/usage-daily.jsonl)从实时记账功能上线起才有数据;本模块把各工作区
|
|
5
|
+
* 里**旧会话**的会话级 usage.jsonl 一次性补进全局账本,/usage 即可看到历史。
|
|
6
|
+
*
|
|
7
|
+
* 扫描来源:全局工作区注册表(~/.mocode/workspaces.jsonl,启动与 /cd 时登记)里的每个
|
|
8
|
+
* 工作区,读 `<root>/.mocode/sessions/<id>/usage.jsonl`。
|
|
9
|
+
*
|
|
10
|
+
* 去重(两层,共同保证任意顺序重复执行都不双算):
|
|
11
|
+
* 1. 行级 `trackedInGlobal`:实时记账上线后产生的 usage 行带此标记,回填直接跳过;
|
|
12
|
+
* 2. 文件级断点 `~/.mocode/usage-import-state.json`:记录每个 usage 文件已导入的行数,
|
|
13
|
+
* 重跑只导入新增的"未标记"行(覆盖"会话在升级前后都活跃"的时间窗口)。
|
|
14
|
+
*
|
|
15
|
+
* 历史记录缺真实时间戳/模型:日期与会话创建时间按 session 目录 id 的时间前缀推断
|
|
16
|
+
* (本地时区),模型取 session.json 的 model(会话最后保存时的模型)。回填行标 source=backfill。
|
|
17
|
+
*/
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import os from 'node:os';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { appendGlobalUsage } from './global-usage.js';
|
|
22
|
+
import { readWorkspaceRegistry } from '../workspace/registry.js';
|
|
23
|
+
const DEFAULT_STATE_PATH = path.join(os.homedir(), '.mocode', 'usage-import-state.json');
|
|
24
|
+
function readState(statePath) {
|
|
25
|
+
try {
|
|
26
|
+
const s = JSON.parse(fs.readFileSync(statePath, 'utf8'));
|
|
27
|
+
return { files: s && typeof s.files === 'object' ? s.files : {} };
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return { files: {} };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function writeState(statePath, state) {
|
|
34
|
+
try {
|
|
35
|
+
fs.mkdirSync(path.dirname(statePath), { recursive: true });
|
|
36
|
+
const tmp = `${statePath}.tmp`;
|
|
37
|
+
fs.writeFileSync(tmp, JSON.stringify(state), 'utf8');
|
|
38
|
+
fs.renameSync(tmp, statePath);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// 状态写失败不致命:最坏是下次重跑时多扫一遍(行级标记仍防双算,见文件头)。
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** session id 时间前缀 → 本地 ISO(无时区串,按机器本地时区)与本地日期;无法解析返回空。 */
|
|
45
|
+
function sessionIdTime(id) {
|
|
46
|
+
const m = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})(?:-(\d{3})-[a-f0-9]{8})?$/.exec(id);
|
|
47
|
+
if (!m)
|
|
48
|
+
return undefined;
|
|
49
|
+
const [, y, mo, d, h, mi, s, ms] = m;
|
|
50
|
+
const day = `${y}-${mo}-${d}`;
|
|
51
|
+
const isoLocal = `${day}T${h}:${mi}:${s}${ms ? `.${ms}` : ''}`;
|
|
52
|
+
return { isoLocal, day };
|
|
53
|
+
}
|
|
54
|
+
/** 列一个工作区的会话目录 id(与 SessionStore.list 的目录识别同规则)。 */
|
|
55
|
+
function listSessionIds(root) {
|
|
56
|
+
const dir = path.join(root, '.mocode', 'sessions');
|
|
57
|
+
try {
|
|
58
|
+
return fs
|
|
59
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
60
|
+
.filter((e) => e.isDirectory() && /^\d{8}-\d{6}(?:-\d{3}-[a-f0-9]{8})?$/.test(e.name))
|
|
61
|
+
.map((e) => e.name);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function readSessionModel(root, id) {
|
|
68
|
+
try {
|
|
69
|
+
const rec = JSON.parse(fs.readFileSync(path.join(root, '.mocode', 'sessions', id, 'session.json'), 'utf8'));
|
|
70
|
+
return typeof rec.model === 'string' ? rec.model : '';
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return '';
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* 执行历史回填。best-effort:单个工作区/会话失败不拖垮整体。
|
|
78
|
+
* @param extraRoots 注册表之外额外扫描的工作区根(如当前工作区)。
|
|
79
|
+
*/
|
|
80
|
+
export function backfillGlobalUsage(opts = {}) {
|
|
81
|
+
const extraRoots = opts.extraRoots ?? [];
|
|
82
|
+
const statePath = opts.statePath ?? DEFAULT_STATE_PATH;
|
|
83
|
+
const roots = [
|
|
84
|
+
...new Set([...readWorkspaceRegistry().map((e) => e.root), ...extraRoots.map((r) => path.resolve(r))]),
|
|
85
|
+
];
|
|
86
|
+
const state = readState(statePath);
|
|
87
|
+
const result = { workspaces: 0, sessions: 0, records: 0, skippedTracked: 0 };
|
|
88
|
+
for (const root of roots) {
|
|
89
|
+
const ids = listSessionIds(root);
|
|
90
|
+
if (ids.length === 0)
|
|
91
|
+
continue;
|
|
92
|
+
result.workspaces++;
|
|
93
|
+
for (const id of ids) {
|
|
94
|
+
const file = path.join(root, '.mocode', 'sessions', id, 'usage.jsonl');
|
|
95
|
+
let rows;
|
|
96
|
+
try {
|
|
97
|
+
// 只保留非空行:游标按"已处理的记录行"计数,避开 split('\n') 末尾空串导致的错位。
|
|
98
|
+
rows = fs
|
|
99
|
+
.readFileSync(file, 'utf8')
|
|
100
|
+
.split('\n')
|
|
101
|
+
.filter((l) => l.trim() !== '');
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
continue; // 该会话无 usage 文件
|
|
105
|
+
}
|
|
106
|
+
const before = state.files[file] ?? 0;
|
|
107
|
+
// 断点只进不退:文件被截断重写(行数变少,轮转/手工)时从头来,否则只处理新增尾部。
|
|
108
|
+
const start = before <= rows.length ? before : 0;
|
|
109
|
+
const tinfo = sessionIdTime(id);
|
|
110
|
+
const model = readSessionModel(root, id) || '(unknown)';
|
|
111
|
+
let touchedSession = false;
|
|
112
|
+
for (let i = start; i < rows.length; i++) {
|
|
113
|
+
const line = rows[i].trim();
|
|
114
|
+
let row;
|
|
115
|
+
try {
|
|
116
|
+
row = JSON.parse(line);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
continue; // 损坏行跳过
|
|
120
|
+
}
|
|
121
|
+
touchedSession = true;
|
|
122
|
+
// live 行已实时计入:只标记跳过,不重复导入。
|
|
123
|
+
if (row.trackedInGlobal) {
|
|
124
|
+
result.skippedTracked++;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (typeof row.inputTokens !== 'number' || typeof row.outputTokens !== 'number')
|
|
128
|
+
continue;
|
|
129
|
+
appendGlobalUsage({
|
|
130
|
+
ts: tinfo?.isoLocal,
|
|
131
|
+
day: tinfo?.day,
|
|
132
|
+
workspace: root,
|
|
133
|
+
model,
|
|
134
|
+
phase: row.phase === 'compact' ? 'compact' : 'main',
|
|
135
|
+
sessionId: id,
|
|
136
|
+
source: 'backfill',
|
|
137
|
+
input: row.inputTokens,
|
|
138
|
+
output: row.outputTokens,
|
|
139
|
+
cached: row.cachedTokens ?? 0,
|
|
140
|
+
reasoning: row.reasoningTokens ?? 0,
|
|
141
|
+
cacheCreation: row.cacheCreationTokens ?? 0,
|
|
142
|
+
});
|
|
143
|
+
result.records++;
|
|
144
|
+
}
|
|
145
|
+
// 游标推进到已处理的记录行数(JSONL 只追加,新行总在尾部)。
|
|
146
|
+
if (rows.length !== before)
|
|
147
|
+
state.files[file] = rows.length;
|
|
148
|
+
if (touchedSession)
|
|
149
|
+
result.sessions++;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
writeState(statePath, state);
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
@@ -12,8 +12,19 @@
|
|
|
12
12
|
import fs from 'node:fs';
|
|
13
13
|
import os from 'node:os';
|
|
14
14
|
import path from 'node:path';
|
|
15
|
-
/**
|
|
15
|
+
/** 全局账本默认路径:跨工作空间,故放 ~/.mocode 而非项目目录。 */
|
|
16
16
|
export const GLOBAL_USAGE_PATH = path.join(os.homedir(), '.mocode', 'usage-daily.jsonl');
|
|
17
|
+
/**
|
|
18
|
+
* 路径覆盖(仅测试用):让账本落到临时目录,避免污染真实 ~/.mocode。
|
|
19
|
+
* 模块在全量测试进程里可能被别的文件先静态 import 而绑定了真实 home,故不能靠改 env。
|
|
20
|
+
*/
|
|
21
|
+
let globalUsagePathOverride;
|
|
22
|
+
export function __setGlobalUsagePath(p) {
|
|
23
|
+
globalUsagePathOverride = p;
|
|
24
|
+
}
|
|
25
|
+
export function getGlobalUsagePath() {
|
|
26
|
+
return globalUsagePathOverride ?? GLOBAL_USAGE_PATH;
|
|
27
|
+
}
|
|
17
28
|
/** 本地日期 YYYY-MM-DD;不引时区库——运行机器本地时间即用户口径的"天"。 */
|
|
18
29
|
export function localDay(d = new Date()) {
|
|
19
30
|
const p = (n) => String(n).padStart(2, '0');
|
|
@@ -22,10 +33,11 @@ export function localDay(d = new Date()) {
|
|
|
22
33
|
/** 追加一行全局用量。任何 I/O 失败静默——记账不能拖垮主流程。 */
|
|
23
34
|
export function appendGlobalUsage(input) {
|
|
24
35
|
try {
|
|
25
|
-
const
|
|
36
|
+
const when = input.ts ? new Date(input.ts) : new Date();
|
|
37
|
+
const day = input.day ?? (Number.isNaN(when.getTime()) ? localDay() : localDay(when));
|
|
26
38
|
const rec = {
|
|
27
|
-
ts:
|
|
28
|
-
day
|
|
39
|
+
ts: Number.isNaN(when.getTime()) ? new Date().toISOString() : when.toISOString(),
|
|
40
|
+
day,
|
|
29
41
|
input: input.input,
|
|
30
42
|
output: input.output,
|
|
31
43
|
cached: input.cached ?? 0,
|
|
@@ -35,9 +47,10 @@ export function appendGlobalUsage(input) {
|
|
|
35
47
|
model: input.model,
|
|
36
48
|
phase: input.phase,
|
|
37
49
|
...(input.sessionId ? { sessionId: input.sessionId } : {}),
|
|
50
|
+
...(input.source === 'backfill' ? { source: 'backfill' } : {}),
|
|
38
51
|
};
|
|
39
|
-
fs.mkdirSync(path.dirname(
|
|
40
|
-
fs.appendFileSync(
|
|
52
|
+
fs.mkdirSync(path.dirname(getGlobalUsagePath()), { recursive: true });
|
|
53
|
+
fs.appendFileSync(getGlobalUsagePath(), `${JSON.stringify(rec)}\n`, 'utf8');
|
|
41
54
|
}
|
|
42
55
|
catch {
|
|
43
56
|
// best-effort, see file header
|
|
@@ -47,7 +60,7 @@ export function appendGlobalUsage(input) {
|
|
|
47
60
|
export function readGlobalUsage() {
|
|
48
61
|
let raw;
|
|
49
62
|
try {
|
|
50
|
-
raw = fs.readFileSync(
|
|
63
|
+
raw = fs.readFileSync(getGlobalUsagePath(), 'utf8');
|
|
51
64
|
}
|
|
52
65
|
catch {
|
|
53
66
|
return [];
|
package/dist/session/index.js
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
export { compactHistory, maybeCompact, capToolResultForHistory, truncateMid, contextState, createContextState, } from './compact.js';
|
|
8
8
|
// ── Context Budget Scheduler 接缝 ────────────────────────────────────────
|
|
9
|
-
// agent/core.ts 在 age-aware sweep 后调用 runScheduler(history, step)
|
|
10
|
-
//
|
|
9
|
+
// agent/core.ts 在 age-aware sweep 后调用 runScheduler(history, step):评估请求占用,
|
|
10
|
+
// 唯一动作是 compact_history;开关关闭时退化为 maybeCompact。
|
|
11
11
|
// repl /compact 命令调 manualCompact(history, focus?):与自动路径共享决策,focus 透传摘要 prompt。
|
|
12
12
|
export { runScheduler, manualCompact, createBudgetScheduler } from './scheduler.js';
|
|
13
13
|
export { newSessionId, saveSession, loadSession, listSessions, sessionDir } from './persist.js';
|
package/dist/session/notes.js
CHANGED
|
@@ -73,14 +73,24 @@ export function renderPlanSection(plan) {
|
|
|
73
73
|
* 与 renderPlanSection 配对(一个写一个读),格式定义与解析同处,避免散落两处走样。
|
|
74
74
|
*/
|
|
75
75
|
export function planStepLabel(raw) {
|
|
76
|
+
const { label, detail } = planStepParts(raw);
|
|
77
|
+
return label || detail || raw.trim();
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* 步骤行正文的完整拆解:短标签 + 详情 + 进行中文案。planStepLabel 的无损版——
|
|
81
|
+
* 底栏 plan chip 点击步骤展开详情时需要 detail(不再只取短标签丢掉描述)。
|
|
82
|
+
* detail 取 `**title** — ` 之后的正文;无 title 的老 plan detail 为空串(整行已当 label)。
|
|
83
|
+
*/
|
|
84
|
+
export function planStepParts(raw) {
|
|
76
85
|
const body = raw.trim();
|
|
77
86
|
const afIdx = body.lastIndexOf('◀');
|
|
78
87
|
const activeForm = afIdx >= 0 ? body.slice(afIdx + 1).trim() : '';
|
|
79
88
|
const main = (afIdx >= 0 ? body.slice(0, afIdx) : body).trim();
|
|
80
89
|
const m = main.match(/^\*\*(.+?)\*\*(?:\s*—\s*)?([\s\S]*)$/);
|
|
81
90
|
const title = m?.[1]?.trim() ?? '';
|
|
82
|
-
const
|
|
83
|
-
|
|
91
|
+
const detail = (m ? (m[2] ?? '') : '').trim();
|
|
92
|
+
const content = m ? detail : main;
|
|
93
|
+
return { label: title || activeForm || content, detail, activeForm };
|
|
84
94
|
}
|
|
85
95
|
/** 读取当前活跃 `## Plan:` 段的标题;无活跃 plan 返 null。 */
|
|
86
96
|
export function readActivePlanTitle(sessionId = getCurrentSessionId()) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Context Budget Scheduler: normal operation is metadata-only. History content is
|
|
2
2
|
// rewritten only after real occupancy reaches the shared pressure threshold.
|
|
3
|
-
import { evaluateBudget, scheduleActions,
|
|
3
|
+
import { evaluateBudget, scheduleActions, DEFAULT_BUDGET_POLICY, } from '../context/budget.js';
|
|
4
4
|
import { chatTools } from '../llm/index.js';
|
|
5
5
|
import { defaultCompactionRuntime, maybeCompact, contextState, } from './compact.js';
|
|
6
6
|
import { pruneStaleArtifacts, refreshArtifactFreshness } from '../context/artifacts.js';
|
|
@@ -8,6 +8,8 @@ import { pruneSuperseded } from '../context/relevance.js';
|
|
|
8
8
|
import { clearRetrievableResults } from '../context/clearing.js';
|
|
9
9
|
import { createAgeAwareEncodingState } from '../context/age-aware.js';
|
|
10
10
|
import { applyImageBudget } from '../context/vision-window.js';
|
|
11
|
+
import { ui } from '../ui/theme.js';
|
|
12
|
+
import * as layout from '../ui/layout.js';
|
|
11
13
|
function emptyPressure(report) {
|
|
12
14
|
return {
|
|
13
15
|
triggered: false,
|
|
@@ -23,6 +25,14 @@ function emptyPressure(report) {
|
|
|
23
25
|
/** One scheduler instance is owned by one agent run. */
|
|
24
26
|
export function createBudgetScheduler(state = contextState, runtime = defaultCompactionRuntime) {
|
|
25
27
|
const evaluate = (history, step, activeTools, ephemeralTokens) => evaluateBudget(history, runtime.config.contextWindowTokens, step, state.correction, activeTools, ephemeralTokens);
|
|
28
|
+
// 断路器:压缩跑完仍站在压力线之上,说明「压不下去」是结构性的(system prompt + 工具 schema
|
|
29
|
+
// 等固定开销本身超线,或存在超大单条)。调度器每个 run 新建一次(等价于一个用户轮),所以
|
|
30
|
+
// 这两个标志天然是 turn 作用域的——与 model-turn.ts 的 overflowCompaction 断路器同口径,
|
|
31
|
+
// 但那边按 turnId 计数是因为它挂在跨轮复用的 runtimeContextState 上,这里不需要。
|
|
32
|
+
// 不设此闸的后果:小窗口模型下每步都会付一次完整摘要(输入上限 0.55×window),并连带让
|
|
33
|
+
// readDedup 全量失效、history 前缀缓存归零,三步损耗叠加。
|
|
34
|
+
let compactStuck = false;
|
|
35
|
+
let compactStuckWarned = false;
|
|
26
36
|
const scheduler = {
|
|
27
37
|
lastRunLog: null,
|
|
28
38
|
async runStep(history, step, activeTools = chatTools, ephemeralTokens = 0, signal) {
|
|
@@ -91,19 +101,35 @@ export function createBudgetScheduler(state = contextState, runtime = defaultCom
|
|
|
91
101
|
pressure.staleArtifacts > 0 ||
|
|
92
102
|
pressure.encodedLogsAndSearches > 0 ||
|
|
93
103
|
pressure.cleared > 0;
|
|
104
|
+
let skippedByBreaker = false;
|
|
94
105
|
for (const _action of actions) {
|
|
106
|
+
if (compactStuck) {
|
|
107
|
+
skippedByBreaker = true;
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
95
110
|
const result = await maybeCompact(history, report, undefined, state, activeTools, signal, runtime);
|
|
96
111
|
compactHistoryCalled = true;
|
|
97
112
|
historyRebuilt ||= result?.historyRebuilt === true;
|
|
98
113
|
contentMutated ||= result?.compacted === true;
|
|
114
|
+
// 压完仍在线上 → 本 run 不再重试。注意不能只判 summarized:noop-shrunk-too-large /
|
|
115
|
+
// noop-protected 同样是「束手无策」,重复调用只是白跑。
|
|
116
|
+
if (result && result.estimateAfter >= pressureLine)
|
|
117
|
+
compactStuck = true;
|
|
118
|
+
}
|
|
119
|
+
// 首次压完超阈时 compact.ts 已经打过一行提示;这里只在**真的又触发、却被断路器挡下**
|
|
120
|
+
// 时补一句,说明"别指望再压一次",避免两次提示措辞打架。
|
|
121
|
+
if (skippedByBreaker && !compactStuckWarned) {
|
|
122
|
+
compactStuckWarned = true;
|
|
123
|
+
layout.contentWrite(` ${ui.yellow}●${ui.reset} ${ui.yellow}本回合已停止重复压缩(压不下去是结构性的:固定开销或超大单条超线);建议 /clear 或改用更大窗口的模型。${ui.reset}\n`);
|
|
99
124
|
}
|
|
100
125
|
const log = {
|
|
101
126
|
step,
|
|
102
127
|
report,
|
|
103
|
-
actions,
|
|
128
|
+
actions: compactStuck ? [] : actions,
|
|
104
129
|
pressure,
|
|
105
130
|
compactHistoryCalled,
|
|
106
131
|
historyMutation: historyRebuilt ? 'rebuild' : contentMutated ? 'content' : 'none',
|
|
132
|
+
breakerOpen: compactStuck,
|
|
107
133
|
ts: Date.now(),
|
|
108
134
|
};
|
|
109
135
|
scheduler.lastRunLog = log;
|
|
@@ -200,4 +226,4 @@ export async function manualCompact(history, focus, opts) {
|
|
|
200
226
|
state.schedulerLog = log;
|
|
201
227
|
return log;
|
|
202
228
|
}
|
|
203
|
-
export { evaluateBudget, scheduleActions
|
|
229
|
+
export { evaluateBudget, scheduleActions };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /usage 按天用量的终端柱状图(替代长表格:300 天的表有 300+ 行,不可用)。
|
|
3
|
+
*
|
|
4
|
+
* 设计:
|
|
5
|
+
* - 固定 CHART_ROWS 行高,区间再长也不增高;天数 > MAX_BARS 时按等宽时间桶聚合
|
|
6
|
+
* (300 天 → 每柱 7 天,约 43 根柱)。
|
|
7
|
+
* - 柱高按 log1p 缩放:日用量从几十 k 到几百 M 跨 4 个数量级,线性柱会让小日全贴底。
|
|
8
|
+
* - x 轴标签等距抽样(MM-DD),柱子密集时不互相叠字。
|
|
9
|
+
*
|
|
10
|
+
* 纯函数:输入每日聚合 + 终端列宽,输出多行 ANSI 字符串(非 markdown,直接 contentWrite)。
|
|
11
|
+
*/
|
|
12
|
+
import { ui } from '../ui/theme.js';
|
|
13
|
+
import { fmtCompactTokens } from '../ui/render.js';
|
|
14
|
+
export const CHART_ROWS = 6;
|
|
15
|
+
/** 柱数上限:超过则按时间桶聚合。 */
|
|
16
|
+
export const MAX_BARS = 48;
|
|
17
|
+
/** 左侧对数标尺占用列宽。 */
|
|
18
|
+
const SCALE_W = 7;
|
|
19
|
+
/** 每日数据 → 柱数据;超过 maxBars 则等宽分桶(桶内求和,标签取桶末日)。 */
|
|
20
|
+
export function bucketizeDays(data, maxBars = MAX_BARS) {
|
|
21
|
+
const n = data.length;
|
|
22
|
+
if (n === 0)
|
|
23
|
+
return [];
|
|
24
|
+
const toBar = (d) => ({
|
|
25
|
+
label: d.day.slice(5),
|
|
26
|
+
total: d.input + d.output,
|
|
27
|
+
input: d.input,
|
|
28
|
+
output: d.output,
|
|
29
|
+
calls: d.calls,
|
|
30
|
+
spanDays: 1,
|
|
31
|
+
});
|
|
32
|
+
if (n <= maxBars)
|
|
33
|
+
return data.map(toBar);
|
|
34
|
+
const size = Math.ceil(n / maxBars);
|
|
35
|
+
const bars = [];
|
|
36
|
+
for (let i = 0; i < n; i += size) {
|
|
37
|
+
const chunk = data.slice(i, i + size);
|
|
38
|
+
const agg = chunk.reduce((acc, d) => {
|
|
39
|
+
acc.input += d.input;
|
|
40
|
+
acc.output += d.output;
|
|
41
|
+
acc.calls += d.calls;
|
|
42
|
+
return acc;
|
|
43
|
+
}, { input: 0, output: 0, calls: 0 });
|
|
44
|
+
bars.push({
|
|
45
|
+
label: chunk[chunk.length - 1].day.slice(5),
|
|
46
|
+
total: agg.input + agg.output,
|
|
47
|
+
input: agg.input,
|
|
48
|
+
output: agg.output,
|
|
49
|
+
calls: agg.calls,
|
|
50
|
+
spanDays: chunk.length,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return bars;
|
|
54
|
+
}
|
|
55
|
+
/** 柱高 → 颜色梯度(顶层黄、高量绿、中量青、低量 dim)。 */
|
|
56
|
+
function bandColor(height) {
|
|
57
|
+
if (height >= CHART_ROWS)
|
|
58
|
+
return ui.yellow;
|
|
59
|
+
if (height >= CHART_ROWS - 2)
|
|
60
|
+
return ui.green;
|
|
61
|
+
if (height >= 2)
|
|
62
|
+
return ui.cyan;
|
|
63
|
+
return ui.dim;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* 渲染柱状图为物理行数组(调用方自行 join '\n')。
|
|
67
|
+
* @param cols 终端列宽;图表总宽钳到 [28, 84]。
|
|
68
|
+
*/
|
|
69
|
+
export function renderUsageBars(bars, cols) {
|
|
70
|
+
if (bars.length === 0 || bars.every((b) => b.total <= 0))
|
|
71
|
+
return [];
|
|
72
|
+
const totalW = Math.max(28, Math.min(cols - 2, 84));
|
|
73
|
+
const plotW = totalW - SCALE_W;
|
|
74
|
+
const slot = Math.max(1, Math.floor(plotW / bars.length));
|
|
75
|
+
const barW = Math.min(3, Math.max(1, slot - 1));
|
|
76
|
+
const maxV = Math.max(...bars.map((b) => b.total));
|
|
77
|
+
const logMax = Math.log1p(maxV);
|
|
78
|
+
const heightOf = (v) => (v <= 0 ? 0 : Math.max(1, Math.round((Math.log1p(v) / logMax) * CHART_ROWS)));
|
|
79
|
+
const scaleCol = (text) => ui.dim + String(text).padStart(SCALE_W - 1) + ' ' + ui.reset;
|
|
80
|
+
const lines = [];
|
|
81
|
+
for (let r = CHART_ROWS; r >= 1; r--) {
|
|
82
|
+
// 仅顶行/底行给对数标尺(最大/最小),中间行留空,省地方也不制造精度错觉。
|
|
83
|
+
let row;
|
|
84
|
+
if (r === CHART_ROWS)
|
|
85
|
+
row = scaleCol(fmtCompactTokens(maxV));
|
|
86
|
+
else if (r === 1)
|
|
87
|
+
row = scaleCol('0');
|
|
88
|
+
else
|
|
89
|
+
row = ' '.repeat(SCALE_W);
|
|
90
|
+
for (const b of bars) {
|
|
91
|
+
const h = heightOf(b.total);
|
|
92
|
+
if (r <= h) {
|
|
93
|
+
const color = bandColor(h);
|
|
94
|
+
row += color + '█'.repeat(barW) + ui.reset + ' '.repeat(Math.max(0, slot - barW));
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
row += ' '.repeat(slot);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
lines.push(row.replace(/\s+$/, ''));
|
|
101
|
+
}
|
|
102
|
+
// x 轴标签:按可用宽度等距抽样,每标签至少 6 列间隔(MM-DD 长 5)。
|
|
103
|
+
const labelEvery = Math.max(1, Math.ceil(6 / slot));
|
|
104
|
+
let axis = ' '.repeat(SCALE_W);
|
|
105
|
+
bars.forEach((b, i) => {
|
|
106
|
+
if (i % labelEvery === 0) {
|
|
107
|
+
// 覆盖该 slot 起点放标签;抽样间隔保证不会与下一个标签相撞。
|
|
108
|
+
axis += ui.dim + b.label + ui.reset + ' '.repeat(Math.max(0, slot * labelEvery - 5));
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
lines.push(axis.replace(/\s+$/, ''));
|
|
112
|
+
return lines;
|
|
113
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** 从 ChatUsage 构造记录;usage 缺失返 null。 */
|
|
2
|
-
export function toUsageRecord(step, phase, usage, estimatedTotal) {
|
|
2
|
+
export function toUsageRecord(step, phase, usage, estimatedTotal, trackedInGlobal = true) {
|
|
3
3
|
if (!usage)
|
|
4
4
|
return null;
|
|
5
5
|
return {
|
|
@@ -11,6 +11,8 @@ export function toUsageRecord(step, phase, usage, estimatedTotal) {
|
|
|
11
11
|
reasoningTokens: usage.reasoningTokens,
|
|
12
12
|
...(usage.cacheCreationTokens ? { cacheCreationTokens: usage.cacheCreationTokens } : {}),
|
|
13
13
|
...(estimatedTotal != null ? { estimatedTotal } : {}),
|
|
14
|
+
// 仅在 true 时落字段:旧记录形状保持最小(且 summarize 不读它)。
|
|
15
|
+
...(trackedInGlobal ? { trackedInGlobal: true } : {}),
|
|
14
16
|
};
|
|
15
17
|
}
|
|
16
18
|
function emptyTotals() {
|
|
@@ -25,12 +25,12 @@ import { t } from '../../i18n/index.js';
|
|
|
25
25
|
import { state } from './state.js';
|
|
26
26
|
import { esc, cup, getGeo, setRegion, runningCaretPos, contentMode } from './screen.js';
|
|
27
27
|
import { normalizeSelection, normalizeInputSelection, extractSelectionText, extractInputSelectionText, isInputRow, pasteIntoInput, inputScreenToInputPos, } from './selection.js';
|
|
28
|
-
import { composePlanLines, drawStatusBar, startTurnTimer, stopTurnTimer } from './statusbar.js';
|
|
28
|
+
import { composePlanLines, drawStatusBar, startTurnTimer, stopTurnTimer, isPlanRow, togglePlanExpanded, togglePlanDetail, setPlanRelayoutHandler, } from './statusbar.js';
|
|
29
29
|
import { paintInput, repaint } from './input-paint.js';
|
|
30
30
|
import { WHEEL_LINES, screenRowToAbsLine, repaintViewport, scrollBy, scrollWheel, resetScroll, lockScrollToBottom, } from './scroll.js';
|
|
31
31
|
import { contentWrite, contentInsertAfter, contentDeleteFrom, contentReplaceLine, reflowContentForResize, flushMdSegment, } from './content-write.js';
|
|
32
32
|
export { isTuiActive, getGeo, getEffectiveContentBottom, setRegion, contentMode, isStreamingPaused } from './screen.js';
|
|
33
|
-
export { drawStatusBar, setStatus, stopTurnTimer, startTurnTimerIfRunning, paintLiveAtCursor, clearLiveAtCursor, setLiveUsage, setQueuedTurn, setStatusBase, setPendingAttachChips, } from './statusbar.js';
|
|
33
|
+
export { drawStatusBar, setStatus, stopTurnTimer, startTurnTimerIfRunning, paintLiveAtCursor, clearLiveAtCursor, setLiveUsage, setQueuedTurn, setStatusBase, setPendingAttachChips, togglePlanExpanded, togglePlanDetail, } from './statusbar.js';
|
|
34
34
|
export { paintInput, paintRunningInput, repaint } from './input-paint.js';
|
|
35
35
|
export { isScrolled, repaintViewport, repaintContentLine, scrollBy, scrollWheel, resetScroll, setMenuReserve, lockScrollToBottom, unlockScroll, isScrollLocked, } from './scroll.js';
|
|
36
36
|
export { contentWrite, writeBanner, rewriteBanner, bannerHeight, contentWriteMd, contentWriteMdOnce, clearContent, rewindContent, writeWelcomeBlock, dismissWelcomeBlock, contentInsertAfter, contentDeleteFrom, totalRows, isLastContentRowBlank, normalizeMutationBoundary, normalizeInputBoundary, contentReplaceLine, notifyContentReset, } from './content-write.js';
|
|
@@ -238,6 +238,14 @@ function handleMouseEvent(e) {
|
|
|
238
238
|
scrollWheel(e.dir);
|
|
239
239
|
return;
|
|
240
240
|
}
|
|
241
|
+
// plan chip 行点击(在滚动区外的固定脚栏):按下记录命中行,release 时按行路由——
|
|
242
|
+
// 标题行=折叠/展开整个计划,步骤行=展开/收起该步详情(见 release 分支)。
|
|
243
|
+
// 不走内容选区——plan 行不属于内容缓冲,screenRowToAbsLine 会把它错误钳到 contentBottom。
|
|
244
|
+
// 面板/picker 期间(mouseEnabled=false)不响应,与其它非滚轮鼠标交互一致,防重排覆盖弹窗。
|
|
245
|
+
if (state.mouseEnabled && e.button === 0 && e.type === 'press' && isPlanRow(e.row)) {
|
|
246
|
+
state.planPressRow = e.row;
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
241
249
|
// 输入行左键点击:INPUT 态(含 intervention 面板,其 cursorChangeHandler 已注册)允许定位光标,
|
|
242
250
|
// 提升用户体验(点哪插哪)。RUNNING 态直接 no-op——光标定位是 INPUT 态交互,运行态
|
|
243
251
|
// typeahead 由键盘体系管理(←/→/Home/End,running-input.ts),不应触发模式切换(见
|
|
@@ -309,6 +317,9 @@ function handleMouseEvent(e) {
|
|
|
309
317
|
return;
|
|
310
318
|
}
|
|
311
319
|
if (e.type === 'drag') {
|
|
320
|
+
// 从 plan 行拖出:视为取消点击(与 batch 摘要行"纯点击才折叠"一致),不展开。
|
|
321
|
+
if (state.planPressRow !== null && !isPlanRow(e.row))
|
|
322
|
+
state.planPressRow = null;
|
|
312
323
|
if (state.inputSelection) {
|
|
313
324
|
// 输入框拖动选区:更新 end,触边不动 scroll(输入框行数有限,无外滚概念);重画底栏。
|
|
314
325
|
const pos = inputScreenToInputPos(e.row, e.col);
|
|
@@ -340,6 +351,20 @@ function handleMouseEvent(e) {
|
|
|
340
351
|
}
|
|
341
352
|
// release(左键)
|
|
342
353
|
state.selecting = false;
|
|
354
|
+
// plan chip 纯点击(press 命中且未拖出):按 planRowStep 映射路由——
|
|
355
|
+
// 标题行(offset 0)= 折叠/展开整个计划;步骤行 = 展开/收起该步详情;指示行(null)= no-op。
|
|
356
|
+
if (state.planPressRow !== null) {
|
|
357
|
+
const pressRow = state.planPressRow;
|
|
358
|
+
state.planPressRow = null;
|
|
359
|
+
if (isPlanRow(e.row)) {
|
|
360
|
+
const stepNo = state.planRowStep[e.row - (g.contentBottom + 1)] ?? null;
|
|
361
|
+
if (stepNo !== null)
|
|
362
|
+
togglePlanDetail(stepNo);
|
|
363
|
+
else if (pressRow === g.contentBottom + 1)
|
|
364
|
+
togglePlanExpanded(); // 仅标题行折叠整个计划
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
343
368
|
// 输入框 release 优先:未拖动 → 清选区(光标已定好);拖动过 → 留高亮等右键复制
|
|
344
369
|
if (state.inputSelection) {
|
|
345
370
|
if (!state.inputSelection.dragged) {
|
|
@@ -505,6 +530,12 @@ export function enterAltScreen() {
|
|
|
505
530
|
// 不动终端窗口背景:底色保持用户终端原色,主题只作用于我们画出的 SGR 颜色。
|
|
506
531
|
stdout.write(esc.mouseOn); // 完整鼠标追踪(按下/拖动/释放/滚轮)→ mouse.swallow 重组 → handleMouseEvent
|
|
507
532
|
mouse.setHandler(handleMouseEvent);
|
|
533
|
+
// plan 展开态导致脚栏高度变化时,drawStatusBar 心跳路径经此回调全幅重排(重画内容区 + 输入区),
|
|
534
|
+
// 避免在 statusbar 层静态 import input-paint 形成循环依赖。
|
|
535
|
+
setPlanRelayoutHandler(() => {
|
|
536
|
+
repaintViewport();
|
|
537
|
+
repaint();
|
|
538
|
+
});
|
|
508
539
|
// 进入 alt screen 前 base 可能已设了 planSummary;按当前 planSummary 重算 planRows,
|
|
509
540
|
// 让首次 setRegion 撑出正确脚栏高(否则 plan 撑 2 行时会被 spinner 行覆盖)。
|
|
510
541
|
if (state.base)
|
|
@@ -593,6 +624,7 @@ export function exitAltScreen() {
|
|
|
593
624
|
state.frameCol = 0;
|
|
594
625
|
mouse.setHandler(null);
|
|
595
626
|
mouse.resetMouse();
|
|
627
|
+
setPlanRelayoutHandler(null);
|
|
596
628
|
state.selection = null;
|
|
597
629
|
state.selecting = false;
|
|
598
630
|
// raw 还原独立 try:非 TTY / 不支持时 setRawMode 抛错,不应阻断 stdout 恢复(alt 退屏必须执行)。
|