mocode-ai 1.9.3 → 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/context/budget.js +19 -81
- package/dist/context/index.js +1 -1
- package/dist/i18n/index.js +10 -12
- package/dist/repl/commands/compact.js +1 -1
- package/dist/repl/commands/stats.js +46 -70
- package/dist/repl/commands.js +4 -1
- package/dist/repl/status-bar.js +35 -12
- 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/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/package.json +1 -1
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ MoCode keeps code-level control light and leaves task strategy to the agent:
|
|
|
41
41
|
- **Advisory working discipline** — The system prompt asks the agent to make focused changes, avoid redundant retrieval, and decide for itself whether validation is useful. Validation is optional and is never a completion gate.
|
|
42
42
|
- **Bounded tool retries, explicit failures** — The runtime automatically retries only transient errors from tools explicitly marked `idempotent`, at most twice. `TIMEOUT`, permission denial, cancellation, and non-idempotent calls are not automatically retried. The resulting structured outcome is returned to the agent for any further recovery decision; see [Automatic retry](#automatic-retry-the-retryable-contract).
|
|
43
43
|
- **`ask_human` for user-owned decisions** — The agent must ask before any decision the user has not made (multiple reasonable approaches) and before key modifications (public APIs, schemas, dependencies, file moves/deletes, architecture, security, large or irreversible changes). Only trivial, repository-precedent details are decided alone.
|
|
44
|
-
- **Five
|
|
44
|
+
- **Five independent context dials + token self-calibration** — `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` each manage one layer of context pressure. Triggering is a single threshold — request occupancy (raw or corrected, whichever is larger) at 80% of the window — not a per-zone quota: a zone being over its share never rewrites anything on its own. Token estimation self-calibrates against provider usage.
|
|
45
45
|
|
|
46
46
|
## Architecture
|
|
47
47
|
|
package/README.zh-CN.md
CHANGED
|
@@ -93,7 +93,7 @@ mocode 把代码层控制保持得尽量轻,把任务策略交给 agent:
|
|
|
93
93
|
- **建议式工作纪律** — system prompt 只要求聚焦改动、避免重复检索、诚实报告不确定性;是否验证及验证范围由 agent 自主决定,不是完成硬门。
|
|
94
94
|
- **有界重试,明确报告失败** — runtime 仅对显式声明 `idempotent` 的工具瞬时错误自动重试,最多两次;`TIMEOUT`、权限拒绝、中断和非幂等调用不自动重试。最终结构化结果交给 agent,由其决定后续恢复方式,详见[自动重试](#自动重试retryable-契约)。
|
|
95
95
|
- **ask_human 决策与关键修改先问** — 用户尚未做出的决策(存在多个合理方案)和关键修改(公共 API、schema、依赖、文件移动/删除、架构、安全、大范围或不可逆改动)必须先询问用户;只有符合仓库惯例的琐碎细节才由 agent 自行决定。
|
|
96
|
-
-
|
|
96
|
+
- **五个独立的上下文旋钮 + token 自校准** — `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` 各管一层上下文压力。触发条件是单一阈值:请求占用(裸估算与校正后取大者)到达窗口的 80%,不是分区配额——某个分区超配额本身不会改写任何内容。token 估算根据真实 provider 用量校准。
|
|
97
97
|
|
|
98
98
|
## 为什么用 mocode
|
|
99
99
|
|
package/dist/context/budget.js
CHANGED
|
@@ -1,28 +1,17 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Context Budget accounting and the shared pressure threshold.
|
|
2
2
|
//
|
|
3
3
|
// This module only estimates and reports. session/scheduler.ts owns the sole
|
|
4
4
|
// automatic rewrite sequence and starts all pressure cleanup plus compact_history
|
|
5
5
|
// when corrected or raw request occupancy reaches 80%.
|
|
6
|
-
|
|
6
|
+
//
|
|
7
|
+
// 产出只有四个标量:total / rawTotal / window / hotBoundary(外加 systemCosts 拆分)。
|
|
8
|
+
// 曾经这里还有一套「五区分账」(system/history/toolRecent/toolOld/summary/reserve 各自的
|
|
9
|
+
// ratio 与 overBudget/overRatio),但它的全部产物只流向一个无人调用的 formatReport(),
|
|
10
|
+
// 调度器从头到尾只看总阈值 —— 留着会让后来的人以为改 ratios 能改变压缩行为,实际零影响。
|
|
11
|
+
// 2026-11 已删除,避免误判。
|
|
12
|
+
import { chatTools, estimateToolSchemaTokens, messageTokens } from '../llm/index.js';
|
|
7
13
|
import { toText } from './utils.js';
|
|
8
|
-
/** 五区分账(占比对齐 CONTEXT_WINDOW)。顺序固定,便于遍历。 */
|
|
9
|
-
export const BUDGET_LAYERS = [
|
|
10
|
-
'system',
|
|
11
|
-
'history',
|
|
12
|
-
'toolRecent', // Hot Tool
|
|
13
|
-
'toolOld', // Cold Tool
|
|
14
|
-
'summary',
|
|
15
|
-
'reserve', // Reserve(不占内容,只占预算分配;5%)
|
|
16
|
-
];
|
|
17
14
|
export const DEFAULT_BUDGET_POLICY = {
|
|
18
|
-
ratios: {
|
|
19
|
-
system: 0.15,
|
|
20
|
-
history: 0.2,
|
|
21
|
-
toolRecent: 0.25,
|
|
22
|
-
toolOld: 0.25,
|
|
23
|
-
summary: 0.1,
|
|
24
|
-
reserve: 0.05,
|
|
25
|
-
},
|
|
26
15
|
hotTurnWindow: 4,
|
|
27
16
|
// 压缩保留区:自动 15% / 强压 5%,且绝对上限 48k——摘要+最近几轮足够续工,
|
|
28
17
|
// 旧 0.40 在大窗口下导致"160k 压到 100k"的无效压缩。
|
|
@@ -30,12 +19,8 @@ export const DEFAULT_BUDGET_POLICY = {
|
|
|
30
19
|
compactForceKeepRatio: 0.05,
|
|
31
20
|
compactKeepMaxTokens: 48000,
|
|
32
21
|
pressureTriggerRatio: 0.8,
|
|
33
|
-
schedulerTargetRatio: 0.8,
|
|
34
|
-
estimateSafetyFactor: 1.05,
|
|
35
|
-
compactHeadroomTokens: 1500,
|
|
36
22
|
};
|
|
37
23
|
/** 兼容既有调用方的只读别名;配置只在 DEFAULT_BUDGET_POLICY 中维护。 */
|
|
38
|
-
export const BUDGET_RATIO = DEFAULT_BUDGET_POLICY.ratios;
|
|
39
24
|
export const HOT_TURN_WINDOW = DEFAULT_BUDGET_POLICY.hotTurnWindow;
|
|
40
25
|
function msgTokens(m) {
|
|
41
26
|
// 与请求预估复用同一实现,避免角色结构开销、多模态和 tool_calls 在两个预算路径中漂移。
|
|
@@ -55,20 +40,17 @@ export function userTurnBoundary(history, window) {
|
|
|
55
40
|
}
|
|
56
41
|
return 1; // 没攒够 N 个 user 之前的全归 Cold(history[0] system 不动)
|
|
57
42
|
}
|
|
58
|
-
/** 评估当前 history
|
|
43
|
+
/** 评估当前 history 的请求占用(纯函数,改不动 history)。
|
|
59
44
|
* 传入 step 是当前所在 step 编号(agent 循环 step 变量),用于日志/调试。
|
|
60
45
|
* correction:API 实测 / 估算的校正系数(默认 1);>1 表示粗估偏低,乘以系数后 actual 更接近真实值。
|
|
61
46
|
* activeTools 必须与下一次 chat() 实际发送的工具集合一致,避免 plan/子 agent 误算 schema。
|
|
62
47
|
* ephemeralTokens:本次请求会追加、但不在 history 里的尾部注入(会话状态提醒等)的裸 token,
|
|
63
48
|
* 必须传入,否则压力线看不见这部分开销(见 SystemCostBreakdown.ephemeral)。 */
|
|
64
49
|
export function evaluateBudget(history, window, step = 0, correction = 1, activeTools = chatTools, ephemeralTokens = 0) {
|
|
65
|
-
const layers = {};
|
|
66
|
-
for (const k of BUDGET_LAYERS) {
|
|
67
|
-
const budget = Math.floor(BUDGET_RATIO[k] * window);
|
|
68
|
-
layers[k] = { actual: 0, budget, overBudget: false, overRatio: 0 };
|
|
69
|
-
}
|
|
70
50
|
// 校正后的 token 数:raw * correction,最小 1(raw > 0 时)。
|
|
71
51
|
const adj = (raw) => (raw > 0 ? Math.max(1, Math.round(raw * correction)) : 0);
|
|
52
|
+
// 校正后总量:逐段累加,不再先分桶再求和。
|
|
53
|
+
let total = 0;
|
|
72
54
|
// 裸总量(不乘 correction):硬闸用它判断,防止 correction 折扣否决真实溢出。
|
|
73
55
|
let rawTotal = 0;
|
|
74
56
|
const sysMsg = history[0];
|
|
@@ -81,7 +63,7 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
|
|
|
81
63
|
// 工具 schema、system prompt 与尾部 ephemeral 注入同属请求固定开销;
|
|
82
64
|
// 必须计入总量才能可靠触发压缩(尾部注入不在 history 里,只能由调用方传入)。
|
|
83
65
|
const systemRaw = systemCosts.prompt + systemCosts.toolSchemas + systemCosts.ephemeralInjection;
|
|
84
|
-
|
|
66
|
+
total += adj(systemRaw);
|
|
85
67
|
rawTotal += systemRaw;
|
|
86
68
|
// Summary 检测:role:'system' 且不是 history[0] 的,视为摘要(compact.ts 摘要插 index 1)。
|
|
87
69
|
// 简单启发:若 history[1]?.role === 'system' 且 content 含「# 会话摘要」特征串,计入 summary。
|
|
@@ -91,55 +73,31 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
|
|
|
91
73
|
const c1 = toText(history[1].content);
|
|
92
74
|
if (c1.startsWith('# 会话摘要') || c1.includes('会话摘要')) {
|
|
93
75
|
const summaryRaw = msgTokens(history[1]);
|
|
94
|
-
|
|
76
|
+
total += adj(summaryRaw);
|
|
95
77
|
rawTotal += summaryRaw;
|
|
96
78
|
summaryHit = true;
|
|
97
79
|
}
|
|
98
80
|
}
|
|
99
81
|
// 划 Hot/Cold 边界
|
|
100
82
|
const hotStart = userTurnBoundary(history, HOT_TURN_WINDOW);
|
|
101
|
-
//
|
|
83
|
+
// tool / user / assistant 一并计入总量(冷热区划分只用于决定改写范围,不影响总量)。
|
|
102
84
|
for (let i = 1; i < history.length; i++) {
|
|
103
85
|
const m = history[i];
|
|
104
86
|
if (i === 1 && summaryHit)
|
|
105
87
|
continue; // summary 已单独算过
|
|
88
|
+
if (m.role === 'system')
|
|
89
|
+
continue; // 其它 system(几乎不存在)跳过
|
|
106
90
|
const raw = msgTokens(m);
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
layers.toolRecent.actual += adj(raw);
|
|
110
|
-
else
|
|
111
|
-
layers.toolOld.actual += adj(raw);
|
|
112
|
-
rawTotal += raw;
|
|
113
|
-
}
|
|
114
|
-
else if (m.role !== 'system') {
|
|
115
|
-
// user / assistant 全部计入 history(对话轨迹)
|
|
116
|
-
layers.history.actual += adj(raw);
|
|
117
|
-
rawTotal += raw;
|
|
118
|
-
}
|
|
119
|
-
// 其它 system(几乎不存在)跳过
|
|
120
|
-
}
|
|
121
|
-
// 计算 overBudget + overRatio
|
|
122
|
-
const triggers = [];
|
|
123
|
-
for (const k of BUDGET_LAYERS) {
|
|
124
|
-
const lb = layers[k];
|
|
125
|
-
if (lb.actual > lb.budget) {
|
|
126
|
-
lb.overBudget = true;
|
|
127
|
-
lb.overRatio = (lb.actual - lb.budget) / Math.max(lb.budget, 1);
|
|
128
|
-
triggers.push(k);
|
|
129
|
-
}
|
|
91
|
+
total += adj(raw);
|
|
92
|
+
rawTotal += raw;
|
|
130
93
|
}
|
|
131
|
-
// 按 overRatio 降序
|
|
132
|
-
triggers.sort((a, b) => layers[b].overRatio - layers[a].overRatio);
|
|
133
|
-
const total = BUDGET_LAYERS.reduce((s, k) => s + (k === 'reserve' ? 0 : layers[k].actual), 0);
|
|
134
94
|
const totalOver = total >= DEFAULT_BUDGET_POLICY.pressureTriggerRatio * window;
|
|
135
95
|
return {
|
|
136
96
|
step,
|
|
137
97
|
total,
|
|
138
98
|
rawTotal,
|
|
139
99
|
window,
|
|
140
|
-
layers,
|
|
141
100
|
systemCosts,
|
|
142
|
-
triggers,
|
|
143
101
|
totalOver,
|
|
144
102
|
hotBoundary: hotStart,
|
|
145
103
|
correction,
|
|
@@ -147,7 +105,7 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
|
|
|
147
105
|
}
|
|
148
106
|
/** 根据 BudgetReport 生成可执行动作。
|
|
149
107
|
* History compaction is the final fallback after pressure-only tool stages.
|
|
150
|
-
*
|
|
108
|
+
* 唯一判定条件是总占用(裸估或校正后的较大者)过 80% 压力线。 */
|
|
151
109
|
export function scheduleActions(report) {
|
|
152
110
|
const actions = [];
|
|
153
111
|
const pressureLine = DEFAULT_BUDGET_POLICY.pressureTriggerRatio * report.window;
|
|
@@ -156,23 +114,3 @@ export function scheduleActions(report) {
|
|
|
156
114
|
}
|
|
157
115
|
return actions;
|
|
158
116
|
}
|
|
159
|
-
/** 拍平成人类可读(供 /context 命令与 check-budget 脚本用)。 */
|
|
160
|
-
export function formatReport(report) {
|
|
161
|
-
const lines = [];
|
|
162
|
-
lines.push(`step ${report.step} total ${report.total}/${report.window} (${((report.total / report.window) * 100).toFixed(1)}%) raw ${report.rawTotal}`);
|
|
163
|
-
for (const k of BUDGET_LAYERS) {
|
|
164
|
-
const lb = report.layers[k];
|
|
165
|
-
const pct = lb.budget > 0 ? ((lb.actual / lb.budget) * 100).toFixed(0) : '-';
|
|
166
|
-
const flag = lb.overBudget ? '⚠' : ' ';
|
|
167
|
-
lines.push(` ${flag} ${k.padEnd(10)} ${String(lb.actual).padStart(6)} / ${String(lb.budget).padStart(6)} (${pct.padStart(3)}%)`);
|
|
168
|
-
}
|
|
169
|
-
if (report.triggers.length > 0) {
|
|
170
|
-
lines.push(` triggers: ${report.triggers.join(' → ')}`);
|
|
171
|
-
}
|
|
172
|
-
return lines.join('\n');
|
|
173
|
-
}
|
|
174
|
-
/** 便捷:把 history 一把估成总 token 数(给 cap.js 等复用,避免重复实现)。
|
|
175
|
-
* 注意:此处是粗估(只看 content 长度),不区分五区——只用于「系统层整体还剩多少」快查。 */
|
|
176
|
-
export function quickEstimate(history) {
|
|
177
|
-
return estimateMessagesTokens(history);
|
|
178
|
-
}
|
package/dist/context/index.js
CHANGED
|
@@ -6,4 +6,4 @@ export { classify, knownToolKinds } from './classifier.js';
|
|
|
6
6
|
export { recordArtifact, invalidateArtifacts, rehydrateArtifacts, refreshArtifactFreshness, pruneStaleArtifacts, collectArtifactRefs, formatArtifactTokenSources, knownEditTargets, } from './artifacts.js';
|
|
7
7
|
export { registerEncoder, registerAll, getEncoder, registeredKinds } from './registry.js';
|
|
8
8
|
// ── Context Budget Scheduler ───────────────────────────────────────────────
|
|
9
|
-
export { evaluateBudget, scheduleActions,
|
|
9
|
+
export { evaluateBudget, scheduleActions, userTurnBoundary, DEFAULT_BUDGET_POLICY, HOT_TURN_WINDOW } from './budget.js';
|
package/dist/i18n/index.js
CHANGED
|
@@ -11,6 +11,7 @@ const zhCN = {
|
|
|
11
11
|
'commands.skills': '列出已发现的 skill',
|
|
12
12
|
'commands.compact': '压缩历史(可带焦点 /compact …)',
|
|
13
13
|
'commands.usage': '跨工作空间按天统计 token 用量(/usage [天数])',
|
|
14
|
+
'commands.usageOverview': '查看最近 7 天 token 用量(可 /usage 30 改天数)',
|
|
14
15
|
'commands.usageImport': '回填各工作区历史会话的 token 用量(幂等)',
|
|
15
16
|
'commands.session': '会话恢复与回滚',
|
|
16
17
|
'commands.sessionResume': '续接最近 10 个已保存会话(快速)',
|
|
@@ -189,6 +190,9 @@ const zhCN = {
|
|
|
189
190
|
'repl.forkDone': '已分叉出新会话 {id}(继承全部上下文,与原会话独立)',
|
|
190
191
|
'repl.forkHint': '本窗口仍在原会话;新终端执行 mocode --resume {id},或在本窗口 /resume 选择该会话',
|
|
191
192
|
'repl.usageTitle': 'Token 用量(全局 · {from} ~ {to} · {days} 天)',
|
|
193
|
+
'repl.usageBarsNote': '按天用量(对数刻度;柱高看相对趋势,精确值见高峰日与排行)',
|
|
194
|
+
'repl.usageBarsBucket': '每柱聚合 {span} 天',
|
|
195
|
+
'repl.usagePeaks': '高峰日:{days}',
|
|
192
196
|
'repl.usageKMetric': '指标',
|
|
193
197
|
'repl.usageKValue': '数值',
|
|
194
198
|
'repl.usageKTotal': '总用量',
|
|
@@ -202,18 +206,12 @@ const zhCN = {
|
|
|
202
206
|
'repl.usageKCacheWrite': '缓存写入',
|
|
203
207
|
'repl.usageKDailyAvg': '日均用量',
|
|
204
208
|
'repl.usageKCompact': '其中压缩(compact)',
|
|
205
|
-
'repl.usageColDate': '日期',
|
|
206
209
|
'repl.usageColWorkspace': '工作空间',
|
|
207
210
|
'repl.usageColModel': '模型',
|
|
208
211
|
'repl.usageColIn': '输入',
|
|
209
212
|
'repl.usageColOut': '输出',
|
|
210
|
-
'repl.usageColCached': '缓存命中',
|
|
211
|
-
'repl.usageColReason': '推理',
|
|
212
213
|
'repl.usageColCalls': '请求数',
|
|
213
|
-
'repl.usageColHit': '命中率',
|
|
214
214
|
'repl.usageColSessions': '会话数',
|
|
215
|
-
'repl.usageEmptyDay': '(无用量)',
|
|
216
|
-
'repl.usageTotalRow': '合计',
|
|
217
215
|
'repl.usageByWorkspace': '按工作空间',
|
|
218
216
|
'repl.usageByModel': '按模型',
|
|
219
217
|
'repl.usageMore': '… 其余 {n} 项已省略',
|
|
@@ -325,6 +323,7 @@ const zhCN = {
|
|
|
325
323
|
'status.queued': '排队 ·',
|
|
326
324
|
'status.queuedCount': '排队 ×{count} ·',
|
|
327
325
|
'status.queuePlanTag': '(Plan)',
|
|
326
|
+
'status.planMoreSteps': '还有 {count} 步',
|
|
328
327
|
'status.measured': '实测',
|
|
329
328
|
'status.estimated': '估算',
|
|
330
329
|
'status.messages': '{count} 条消息',
|
|
@@ -522,6 +521,7 @@ const en = {
|
|
|
522
521
|
'commands.skills': 'List discovered skills',
|
|
523
522
|
'commands.compact': 'Compact history (optional focus: /compact …)',
|
|
524
523
|
'commands.usage': 'Cross-workspace daily token usage (/usage [days])',
|
|
524
|
+
'commands.usageOverview': 'Show token usage for the last 7 days (try /usage 30)',
|
|
525
525
|
'commands.usageImport': 'Backfill token usage from historical sessions (idempotent)',
|
|
526
526
|
'commands.session': 'Resume sessions and roll back turns',
|
|
527
527
|
'commands.sessionResume': 'Resume one of the 10 latest saved sessions',
|
|
@@ -695,6 +695,9 @@ const en = {
|
|
|
695
695
|
'repl.forkDone': 'Forked new session {id} (inherits full context; independent from the original)',
|
|
696
696
|
'repl.forkHint': 'This window stays on the original session; run mocode --resume {id} in a new terminal, or use /resume here',
|
|
697
697
|
'repl.usageTitle': 'Token usage (global · {from} ~ {to} · {days}d)',
|
|
698
|
+
'repl.usageBarsNote': 'Daily usage (log scale; bar height shows relative trend, see peaks and rankings for values)',
|
|
699
|
+
'repl.usageBarsBucket': 'each bar aggregates {span} days',
|
|
700
|
+
'repl.usagePeaks': 'Peak days: {days}',
|
|
698
701
|
'repl.usageKMetric': 'Metric',
|
|
699
702
|
'repl.usageKValue': 'Value',
|
|
700
703
|
'repl.usageKTotal': 'Total tokens',
|
|
@@ -708,18 +711,12 @@ const en = {
|
|
|
708
711
|
'repl.usageKCacheWrite': 'Cache write',
|
|
709
712
|
'repl.usageKDailyAvg': 'Daily average',
|
|
710
713
|
'repl.usageKCompact': 'of which compact',
|
|
711
|
-
'repl.usageColDate': 'Date',
|
|
712
714
|
'repl.usageColWorkspace': 'Workspace',
|
|
713
715
|
'repl.usageColModel': 'Model',
|
|
714
716
|
'repl.usageColIn': 'Input',
|
|
715
717
|
'repl.usageColOut': 'Output',
|
|
716
|
-
'repl.usageColCached': 'Cached',
|
|
717
|
-
'repl.usageColReason': 'Reasoning',
|
|
718
718
|
'repl.usageColCalls': 'Requests',
|
|
719
|
-
'repl.usageColHit': 'Hit rate',
|
|
720
719
|
'repl.usageColSessions': 'Sessions',
|
|
721
|
-
'repl.usageEmptyDay': '(no usage)',
|
|
722
|
-
'repl.usageTotalRow': 'Total',
|
|
723
720
|
'repl.usageByWorkspace': 'By workspace',
|
|
724
721
|
'repl.usageByModel': 'By model',
|
|
725
722
|
'repl.usageMore': '… {n} more hidden',
|
|
@@ -830,6 +827,7 @@ const en = {
|
|
|
830
827
|
'status.queued': 'queued ·',
|
|
831
828
|
'status.queuedCount': 'queued ×{count} ·',
|
|
832
829
|
'status.queuePlanTag': ' (Plan)',
|
|
830
|
+
'status.planMoreSteps': '{count} more step(s)',
|
|
833
831
|
'status.measured': 'measured',
|
|
834
832
|
'status.estimated': 'estimated',
|
|
835
833
|
'status.messages': '{count} messages',
|
|
@@ -32,7 +32,7 @@ export const compactCommands = [
|
|
|
32
32
|
}
|
|
33
33
|
else if (rest)
|
|
34
34
|
focus = rest;
|
|
35
|
-
//
|
|
35
|
+
// 走调度器路径:与自动每步压缩完全一致——先跑零成本清理(cold tools 优先),最后才 LLM 摘要。
|
|
36
36
|
// focus 透传到 compact_history action 的 LLM 摘要 prompt。
|
|
37
37
|
// 返回 SchedulerRunLog 给 UI 显示决策;退化路径(开关关时)在 manualCompact 内部走 compactHistory。
|
|
38
38
|
const log = await (async () => {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 用量命令组:/stats(当前会话诊断)· /usage(
|
|
2
|
+
* 用量命令组:/stats(当前会话诊断)· /usage(跨工作空间用量)
|
|
3
3
|
*
|
|
4
4
|
* /stats 读会话级 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
|
|
5
|
-
* /usage 读全局账本 ~/.mocode/usage-daily.jsonl(
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* /usage 读全局账本 ~/.mocode/usage-daily.jsonl:总览两行 + 固定高度柱状图(长区间
|
|
6
|
+
* 自动按周聚合,替代会撑出几百行的按天表格)+ 高峰日 Top5 + 工作区/模型 Top5 表。
|
|
7
|
+
* /usage import 回填历史会话 usage.jsonl(幂等)。
|
|
8
8
|
*/
|
|
9
9
|
import * as layout from '../../ui/layout.js';
|
|
10
10
|
import { ui } from '../../ui/theme.js';
|
|
@@ -13,6 +13,7 @@ import { t } from '../../i18n/index.js';
|
|
|
13
13
|
import { getActiveSessionStore } from '../../session/store.js';
|
|
14
14
|
import { formatUsageSummary, summarizeUsage } from '../../session/usage-stats.js';
|
|
15
15
|
import { readGlobalUsage, summarizeGlobalUsage, } from '../../session/global-usage.js';
|
|
16
|
+
import { bucketizeDays, renderUsageBars } from '../../session/usage-chart.js';
|
|
16
17
|
import { backfillGlobalUsage } from '../../session/backfill-usage.js';
|
|
17
18
|
import { getWorkspaceRoot } from '../../workspace/index.js';
|
|
18
19
|
import { unhandled, next } from './types.js';
|
|
@@ -35,6 +36,13 @@ function mdTable(headers, rows, align) {
|
|
|
35
36
|
lines.push(`| ${row.join(' | ')} |`);
|
|
36
37
|
return lines.join('\n');
|
|
37
38
|
}
|
|
39
|
+
/** 工作区/模型排行表(Top 5)。 */
|
|
40
|
+
function groupTable(title, colName, rows) {
|
|
41
|
+
const body = rows.slice(0, 5).map((r) => [r.key, tok(r.input), tok(r.output), n(r.calls), n(r.sessions)]);
|
|
42
|
+
return (`${ui.accent}${title}${ui.reset}\n\n` +
|
|
43
|
+
mdTable([colName, t('repl.usageColIn'), t('repl.usageColOut'), t('repl.usageColCalls'), t('repl.usageColSessions')], body, ['l', 'r', 'r', 'r', 'r']) +
|
|
44
|
+
(rows.length > 5 ? `\n\n${ui.dim}${t('repl.usageMore', { n: rows.length - 5 })}${ui.reset}` : ''));
|
|
45
|
+
}
|
|
38
46
|
/** 汇总指标键值表(两列)。 */
|
|
39
47
|
function overviewTable(s) {
|
|
40
48
|
const b = s.total;
|
|
@@ -58,61 +66,39 @@ function overviewTable(s) {
|
|
|
58
66
|
}
|
|
59
67
|
return mdTable([t('repl.usageKMetric'), t('repl.usageKValue')], rows, ['l', 'r']);
|
|
60
68
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
dash,
|
|
70
|
-
dash,
|
|
71
|
-
dash,
|
|
72
|
-
`${ui.dim}${t('repl.usageEmptyDay')}${ui.reset}`,
|
|
73
|
-
];
|
|
74
|
-
}
|
|
75
|
-
return [
|
|
76
|
-
`${ui.cyan}${d.day}${ui.reset}`,
|
|
77
|
-
tok(d.input),
|
|
78
|
-
tok(d.output),
|
|
79
|
-
tok(d.cached),
|
|
80
|
-
tok(d.reasoning),
|
|
81
|
-
n(d.calls),
|
|
82
|
-
pct(d.cached, d.input),
|
|
83
|
-
];
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
/** 按天表:无用量日整行 dim,数字列右对齐,末行合计(每个着色单元格自带 reset 防串色)。 */
|
|
87
|
-
function dailyTable(s) {
|
|
88
|
-
const rows = dayRows(s.byDay);
|
|
89
|
-
const b = s.total;
|
|
90
|
-
const bold = (v) => `${ui.bold}${v}${ui.reset}`;
|
|
91
|
-
rows.push([
|
|
92
|
-
bold(t('repl.usageTotalRow')),
|
|
93
|
-
bold(tok(b.input)),
|
|
94
|
-
bold(tok(b.output)),
|
|
95
|
-
bold(tok(b.cached)),
|
|
96
|
-
bold(tok(b.reasoning)),
|
|
97
|
-
bold(n(b.calls)),
|
|
98
|
-
bold(pct(b.cached, b.input)),
|
|
99
|
-
]);
|
|
100
|
-
return mdTable([
|
|
101
|
-
t('repl.usageColDate'),
|
|
102
|
-
t('repl.usageColIn'),
|
|
103
|
-
t('repl.usageColOut'),
|
|
104
|
-
t('repl.usageColCached'),
|
|
105
|
-
t('repl.usageColReason'),
|
|
106
|
-
t('repl.usageColCalls'),
|
|
107
|
-
t('repl.usageColHit'),
|
|
108
|
-
], rows, ['l', 'r', 'r', 'r', 'r', 'r', 'r']);
|
|
69
|
+
/** 高峰日 Top5:一行紧凑文本(图给趋势,这里给精确值)。 */
|
|
70
|
+
function peaksLine(byDay) {
|
|
71
|
+
const top = byDay
|
|
72
|
+
.filter((d) => d.calls > 0)
|
|
73
|
+
.sort((a, b) => b.input + b.output - (a.input + a.output))
|
|
74
|
+
.slice(0, 5)
|
|
75
|
+
.map((d) => `${d.day.slice(5)} ${tok(d.input + d.output)}`);
|
|
76
|
+
return top.length ? `${ui.dim}${t('repl.usagePeaks', { days: top.join(' · ') })}${ui.reset}` : '';
|
|
109
77
|
}
|
|
110
|
-
/**
|
|
111
|
-
function
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
78
|
+
/** 渲染 /usage 主体:总览表 → 柱状图 → 高峰日 → 排行两表。 */
|
|
79
|
+
function renderUsageReport(s) {
|
|
80
|
+
layout.contentWrite(`\n${ui.accent}${t('repl.usageTitle', { from: s.fromDay, to: s.toDay, days: s.days })}${ui.reset}\n\n`);
|
|
81
|
+
layout.contentWriteMdOnce(overviewTable(s));
|
|
82
|
+
layout.contentWrite('\n\n');
|
|
83
|
+
const buckets = bucketizeDays(s.byDay);
|
|
84
|
+
const bars = renderUsageBars(buckets, layout.getGeo().cols);
|
|
85
|
+
if (bars.length) {
|
|
86
|
+
for (const line of bars)
|
|
87
|
+
layout.contentWrite(` ${line}\n`);
|
|
88
|
+
layout.contentWrite(` ${ui.dim}${t('repl.usageBarsNote')}${ui.reset}\n`);
|
|
89
|
+
const span = buckets[buckets.length - 1]?.spanDays ?? 1;
|
|
90
|
+
if (span > 1) {
|
|
91
|
+
layout.contentWrite(` ${ui.dim}${t('repl.usageBarsBucket', { span })}${ui.reset}\n`);
|
|
92
|
+
}
|
|
93
|
+
const peaks = peaksLine(s.byDay);
|
|
94
|
+
if (peaks)
|
|
95
|
+
layout.contentWrite(` ${peaks}\n`);
|
|
96
|
+
layout.contentWrite('\n');
|
|
97
|
+
}
|
|
98
|
+
layout.contentWriteMdOnce(groupTable(t('repl.usageByWorkspace'), t('repl.usageColWorkspace'), s.byWorkspace));
|
|
99
|
+
layout.contentWrite('\n\n');
|
|
100
|
+
layout.contentWriteMdOnce(groupTable(t('repl.usageByModel'), t('repl.usageColModel'), s.byModel));
|
|
101
|
+
layout.contentWrite('\n');
|
|
116
102
|
}
|
|
117
103
|
export const statsCommands = [
|
|
118
104
|
// /usage import:把各工作区旧会话的 usage.jsonl 回填进全局账本(幂等,可重复执行)。
|
|
@@ -136,7 +122,7 @@ export const statsCommands = [
|
|
|
136
122
|
}
|
|
137
123
|
return next();
|
|
138
124
|
},
|
|
139
|
-
// /usage [days]
|
|
125
|
+
// /usage [days]:跨工作空间用量。默认 7 天,可传天数(如 /usage 300);非法参数给用法提示。
|
|
140
126
|
(ctx) => {
|
|
141
127
|
if (ctx.line !== '/usage' && !ctx.line.startsWith('/usage '))
|
|
142
128
|
return unhandled();
|
|
@@ -155,17 +141,7 @@ export const statsCommands = [
|
|
|
155
141
|
layout.contentWrite(`${ui.dim}${t('repl.usageNoData')}${ui.reset}\n`);
|
|
156
142
|
return next();
|
|
157
143
|
}
|
|
158
|
-
|
|
159
|
-
// 标题与普通文案走裸通道;表格逐个走 md 通道(各自独立渲染,避免跨段识别问题)。
|
|
160
|
-
layout.contentWrite(`\n${ui.accent}${t('repl.usageTitle', { from: s.fromDay, to: s.toDay, days: s.days })}${ui.reset}\n\n`);
|
|
161
|
-
layout.contentWriteMdOnce(overviewTable(s));
|
|
162
|
-
layout.contentWrite('\n\n');
|
|
163
|
-
layout.contentWriteMdOnce(dailyTable(s));
|
|
164
|
-
layout.contentWrite('\n\n');
|
|
165
|
-
layout.contentWriteMdOnce(groupTable(t('repl.usageByWorkspace'), t('repl.usageColWorkspace'), s.byWorkspace));
|
|
166
|
-
layout.contentWrite('\n\n');
|
|
167
|
-
layout.contentWriteMdOnce(groupTable(t('repl.usageByModel'), t('repl.usageColModel'), s.byModel));
|
|
168
|
-
layout.contentWrite('\n');
|
|
144
|
+
renderUsageReport(summarizeGlobalUsage(records, days));
|
|
169
145
|
return next();
|
|
170
146
|
},
|
|
171
147
|
(ctx) => {
|
package/dist/repl/commands.js
CHANGED
|
@@ -27,7 +27,10 @@ export function buildSlashCommands() {
|
|
|
27
27
|
{
|
|
28
28
|
name: '/usage',
|
|
29
29
|
desc: d('commands.usage'),
|
|
30
|
-
children: [
|
|
30
|
+
children: [
|
|
31
|
+
{ name: 'overview', value: '/usage', desc: d('commands.usageOverview') },
|
|
32
|
+
{ name: 'import', value: '/usage import', desc: d('commands.usageImport') },
|
|
33
|
+
],
|
|
31
34
|
},
|
|
32
35
|
{ name: '/stats', desc: '查看本会话 token 用量与缓存命中率' },
|
|
33
36
|
{ name: '/effort', desc: '设置思考强度(/effort [low|medium|high|auto])' },
|
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
|
}
|
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
|
+
}
|
|
@@ -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 退屏必须执行)。
|
|
@@ -135,6 +135,14 @@ export function paintInput(view) {
|
|
|
135
135
|
startVis: 0,
|
|
136
136
|
}
|
|
137
137
|
: windowInputVis(view.lines, view.cursorLine, view.cursorCol, preGeo.cols, promptW, preGeo.rows);
|
|
138
|
+
// 先按本帧输入行数 + 屏幕高度给 plan 区域算精确行数预算(展开态可能占多行),
|
|
139
|
+
// composePlanLines 据此钳制 planRows,随后 needFooterH 才能与实际渲染行数一致。
|
|
140
|
+
// 约束:footerH = 5 + inputRows + (planRows-1) ≤ rows-1(至少留 1 行内容区)。
|
|
141
|
+
state.inputRows = vis.inputRows;
|
|
142
|
+
// 约束:needFooterH = 5+inputRows+(planRows-1) ≤ rows-1(至少留 1 行内容区)
|
|
143
|
+
// → planRows ≤ rows-5-inputRows。展开 20 步的大计划在矮终端里由此钳制。
|
|
144
|
+
const planMaxRows = Math.max(1, preGeo.rows - 5 - vis.inputRows);
|
|
145
|
+
const planLines = composePlanLines(state.base, preGeo.cols, planMaxRows);
|
|
138
146
|
const needFooterH = 5 + vis.inputRows + (state.planRows - 1); // 1 虚拟空 + 1 spinner 行 + 1 上线 + 输入行 + 1 下线 + 1 model 行 + plan 多出的行数
|
|
139
147
|
let g = preGeo;
|
|
140
148
|
if (needFooterH !== state.footerH) {
|
|
@@ -157,24 +165,18 @@ export function paintInput(view) {
|
|
|
157
165
|
buf += cup(effBottom, 1) + esc.clearLine + line;
|
|
158
166
|
}
|
|
159
167
|
// 2c. 虚拟空行(内容区与状态栏之间的视觉间隔,属底栏非内容):
|
|
160
|
-
// - 有活跃 plan:渲染 plan chip(
|
|
168
|
+
// - 有活跃 plan:渲染 plan chip——折叠 1 行摘要,点击展开后逐行列全部步骤(行数按 2. 的预算钳制)
|
|
161
169
|
// - 否则有待发图片附件:渲染附件 chip(不进内容缓冲,提交后由 echoInput 正式回显)
|
|
162
170
|
// - 都没有:清空保留作分隔
|
|
163
|
-
//
|
|
164
|
-
// paintInput 与 drawStatusBar 共享同一 planRows 模块态,setRegion 已据此把脚栏撑高。
|
|
171
|
+
// setRegion 已按 planRows 撑高脚栏,spinner/上线/输入行随之下移。
|
|
165
172
|
{
|
|
166
|
-
|
|
167
|
-
for (let i = 0; i <
|
|
168
|
-
buf += cup(g.contentBottom + 1 + i, 1) + esc.clearLine +
|
|
169
|
-
}
|
|
170
|
-
// 计划行从 2 行降到 1 行(plan 当前很短):清掉残留的第 2 行,不留尾巴。
|
|
171
|
-
if (planBuf.length < state.planRows && state.planRows === 2) {
|
|
172
|
-
buf += cup(g.contentBottom + 2, 1) + esc.clearLine;
|
|
173
|
-
state.planRows = 1;
|
|
173
|
+
// 复用步骤 2. 已按精确预算算好的 plan 行(planRows 已写入 state),此处不再重算。
|
|
174
|
+
for (let i = 0; i < planLines.length; i++) {
|
|
175
|
+
buf += cup(g.contentBottom + 1 + i, 1) + esc.clearLine + planLines[i];
|
|
174
176
|
}
|
|
175
177
|
// 无 plan 时:画待发附件脚栏(chip + 降采样 badge + 非视觉预警,不进内容缓冲);
|
|
176
178
|
// slash 菜单向上展开时最后一行也落在这一行,会互相覆盖——菜单打开期间隐藏(关菜单恢复)。
|
|
177
|
-
if (
|
|
179
|
+
if (planLines.length === 0) {
|
|
178
180
|
const attLine = view.menu && view.menu.lines.length > 0 ? '' : composePendingAttachLine(g.cols);
|
|
179
181
|
buf += cup(g.contentBottom + 1, 1) + esc.clearLine + attLine;
|
|
180
182
|
}
|
|
@@ -79,10 +79,23 @@ export const state = {
|
|
|
79
79
|
spinnerFrame: undefined,
|
|
80
80
|
turnStart: null, // RUNNING 态起点(Date.now());INPUT 态为 null。composeStatus 据此拼走时。
|
|
81
81
|
turnTimer: null, // 走时刷新计时器(独立于 spinner):流式期间 spinner 停转,由它续刷状态行。
|
|
82
|
-
/** 当前 plan chip
|
|
83
|
-
*
|
|
84
|
-
*
|
|
82
|
+
/** 当前 plan chip 占用脚栏行数:折叠=1(摘要行;超长仍单行截断),展开=1+步骤行数(按脚栏剩余高度钳制)。
|
|
83
|
+
* composePlanLines 每次重算后写入。驱动 paintInput setRegion(fh) 动态撑高脚栏;drawStatusBar
|
|
84
|
+
* 据此画 plan 各行,与 spinner/上线/输入/下线/model 行的 +1/+2/+3/+4/+5 偏移天然一致(contentBottom 自动重算)。 */
|
|
85
85
|
planRows: 1,
|
|
86
|
+
/** plan chip 展开态(点击摘要行切换)。planKey 变化(新计划/结算消失)时自动回 false。 */
|
|
87
|
+
planExpanded: false,
|
|
88
|
+
/** 当前已渲染 plan 的身份(标题);与 base.planKey 不同说明 plan 换了,收起展开态。 */
|
|
89
|
+
planStateKey: undefined,
|
|
90
|
+
/** 当前输入框可视行数(paintInput 每帧写入):drawStatusBar 路径钳制展开 plan 高度时需要它算脚栏预算。 */
|
|
91
|
+
inputRows: 1,
|
|
92
|
+
/** 左键按下的屏幕行(release 未拖出 plan 区才触发,与内容区选区/折叠交互同构);null=未按在 plan 行上。 */
|
|
93
|
+
planPressRow: null,
|
|
94
|
+
/** 点击展开详情的步骤号集合(仅展开态有意义);planKey 变化时清空。 */
|
|
95
|
+
planOpenSteps: new Set(),
|
|
96
|
+
/** 展开态行→步骤号映射(plan 区内第 i 行对应哪一步;0=标题行→null)。composePlanLines 每次重建,
|
|
97
|
+
* 鼠标 release 时据此把点击行路由到「折叠整个计划 / 切换某步详情」。 */
|
|
98
|
+
planRowStep: [],
|
|
86
99
|
runningFrame: -1, // 运行态状态行 chip 心跳帧(转圈帧 明灭);INPUT 态 -1 退回静态 ●
|
|
87
100
|
/** 上一次 paintLiveAtCursor 实际画帧的屏坐标(0=未画)。clearLiveAtCursor 清"这行"而非当前续写位——
|
|
88
101
|
* 防 spinner 运行期间续写位漂移时清错行、旧帧行残留(见 557e678 移除 isStreamingPaused 后的间歇性 frame 泄漏)。 */
|
|
@@ -6,7 +6,7 @@ import { ui } from '../theme.js';
|
|
|
6
6
|
import * as content from '../content.js';
|
|
7
7
|
import { t } from '../../i18n/index.js';
|
|
8
8
|
import { state } from './state.js';
|
|
9
|
-
import { esc, cup, getGeo, runningCaretPos, isStreamingPaused } from './screen.js';
|
|
9
|
+
import { esc, cup, getGeo, setRegion, runningCaretPos, isStreamingPaused } from './screen.js';
|
|
10
10
|
const RUNNING_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
11
11
|
// ── 状态行(两行式:spinner 行 + model 行)──
|
|
12
12
|
const STATUS_SEP = ' ';
|
|
@@ -171,33 +171,202 @@ function formatLiveUsageChip(u) {
|
|
|
171
171
|
const cacheTag = cached > 0 ? ` ↻ ${fmt(cached)}` : '';
|
|
172
172
|
return `${ui.dim}↑ ${fmt(billable)} ↓ ${fmt(u.completionTokens)}${cacheTag}${ui.reset}`;
|
|
173
173
|
}
|
|
174
|
-
/**
|
|
175
|
-
|
|
174
|
+
/** plan chip 步骤行的缩进(箭头 1 + 空格 1,步骤行对齐到摘要标题之后两列)。 */
|
|
175
|
+
const PLAN_STEP_INDENT = ' ';
|
|
176
|
+
/** 判断屏幕行是否落在 plan chip 占用的脚栏行(contentBottom+1 .. +planRows)。鼠标命中用。 */
|
|
177
|
+
export function isPlanRow(screenRow) {
|
|
178
|
+
if (!state.active || !state.base?.planSummary)
|
|
179
|
+
return false;
|
|
180
|
+
const g = getGeo();
|
|
181
|
+
return screenRow >= g.contentBottom + 1 && screenRow <= g.contentBottom + state.planRows;
|
|
182
|
+
}
|
|
183
|
+
/** 按显示宽度贪心折行(优先在空格断,宽字符/CJK 整字不拆)。plan 步骤详情用;纯展示,不处理 ANSI。 */
|
|
184
|
+
function wrapDisplayText(text, width) {
|
|
185
|
+
const out = [];
|
|
186
|
+
let line = '';
|
|
187
|
+
let lastSpace = -1; // line 内最后一个空格的 code-unit 下标
|
|
188
|
+
for (const ch of text.replace(/\s+/g, ' ').trim()) {
|
|
189
|
+
if (line && displayWidth(line) + displayWidth(ch) > width) {
|
|
190
|
+
if (lastSpace > 0) {
|
|
191
|
+
out.push(line.slice(0, lastSpace));
|
|
192
|
+
line = line.slice(lastSpace + 1);
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
out.push(line);
|
|
196
|
+
line = '';
|
|
197
|
+
}
|
|
198
|
+
lastSpace = -1;
|
|
199
|
+
}
|
|
200
|
+
if (ch === ' ') {
|
|
201
|
+
if (line) {
|
|
202
|
+
lastSpace = line.length;
|
|
203
|
+
line += ch;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
line += ch;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (line)
|
|
211
|
+
out.push(line);
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* spinner 行上方的「虚拟空行」(contentBottom+1)。
|
|
216
|
+
* - 有活跃 plan 且折叠:显「▸ plan: <summary> (N/M) ▸ 当前步」整行(yellow),过长截 1 行 + "…"
|
|
217
|
+
* - 有活跃 plan 且展开(点击标题行切换):首行「▾ plan: <标题> (N/M)」,下面逐行列全部步骤
|
|
218
|
+
* 「✓ N. label」(完成,dim green)/「▸ N. label」(当前,accent)/「· N. label」(待办,dim);
|
|
219
|
+
* 步骤带 detail 时行尾加 ▸ 提示可点,点击该步在下方缩进展开详情(dim,按宽折行),再点收起。
|
|
220
|
+
* 总行数按脚栏剩余高度(maxRows)钳制,放不下时末行显「… 还有 K 步」。
|
|
176
221
|
* - 无活跃 plan:空(保留原分隔视觉,避免内容贴输入区)
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
|
|
182
|
-
export function composePlanLines(status, cols) {
|
|
222
|
+
* 脚栏高度 = 5 + 输入行 + (planRows-1),spinner/输入/下线/model 行偏移稳定。
|
|
223
|
+
* 这组行在 DECSTBM 滚动区外([1, contentBottom]),稳定不滚。
|
|
224
|
+
* 副作用:重建 state.planRowStep(行→步骤号映射,鼠标点击路由用)。
|
|
225
|
+
* @param maxRows plan 区域允许占用的最大行数;不传时按屏幕高度保守钳(只防顶到屏顶)。
|
|
226
|
+
*/
|
|
227
|
+
export function composePlanLines(status, cols, maxRows) {
|
|
183
228
|
const plan = (status.planSummary ?? '').trim();
|
|
184
229
|
if (!plan) {
|
|
185
230
|
state.planRows = 1;
|
|
231
|
+
state.planExpanded = false;
|
|
232
|
+
state.planStateKey = undefined;
|
|
233
|
+
state.planRowStep = [];
|
|
186
234
|
return [];
|
|
187
235
|
}
|
|
188
|
-
|
|
189
|
-
|
|
236
|
+
// plan 身份变化(新计划 / 结算后新计划):自动收起展开态并清空步骤详情展开集,
|
|
237
|
+
// 避免把旧计划的多行展开套到新计划上。
|
|
238
|
+
if (status.planKey !== state.planStateKey) {
|
|
239
|
+
state.planStateKey = status.planKey;
|
|
240
|
+
state.planExpanded = false;
|
|
241
|
+
state.planOpenSteps.clear();
|
|
242
|
+
}
|
|
243
|
+
const collapsedLine = (caret) => {
|
|
244
|
+
const w = displayWidth(stripAnsi(plan)) + 2; // 箭头 + 空格
|
|
245
|
+
// 颜色必须套在 plan 文本上且在 caret 之后:caret 自带 reset,若 yellow 放在
|
|
246
|
+
// caret 前面会被它清掉,plan 文本就裸奔成默认白(展开态首行尤明显)。
|
|
247
|
+
if (w <= cols)
|
|
248
|
+
return `${caret} ${ui.yellow}${plan}${ui.reset}`;
|
|
249
|
+
return `${caret} ${ui.yellow}${truncateDisplay(plan, Math.max(1, cols - 3))}…${ui.reset}`;
|
|
250
|
+
};
|
|
251
|
+
if (!state.planExpanded) {
|
|
190
252
|
state.planRows = 1;
|
|
191
|
-
|
|
253
|
+
state.planRowStep = [null];
|
|
254
|
+
return [collapsedLine(`${ui.dim}▸${ui.reset}`)];
|
|
192
255
|
}
|
|
193
|
-
//
|
|
194
|
-
|
|
195
|
-
|
|
256
|
+
// ── 展开态:标题行 + 每步一行 + 点开的步骤渲染详情(钳高)──
|
|
257
|
+
const steps = status.planSteps ?? [];
|
|
258
|
+
// 不传 maxRows(drawStatusBar 路径):按屏幕高度保守钳,至少 2 行(标题 + 1 步);
|
|
259
|
+
// 传了(paintInput 路径,已知脚栏预算):精确钳,保证不覆盖 spinner/输入区。
|
|
260
|
+
const cap = Math.max(2, maxRows ?? Math.max(2, getGeo().rows - 5 - state.inputRows));
|
|
261
|
+
const header = collapsedLine(`${ui.accent}▾${ui.reset}`);
|
|
262
|
+
const lines = [header];
|
|
263
|
+
state.planRowStep = [null];
|
|
264
|
+
// 详情详情宽 = 减去详情缩进 4 列;先算好每个点开步骤的详情折行,供预算裁剪。
|
|
265
|
+
const detailIndent = ' ';
|
|
266
|
+
const detailOf = new Map();
|
|
267
|
+
for (const s of steps) {
|
|
268
|
+
if (s.detail && state.planOpenSteps.has(s.no)) {
|
|
269
|
+
detailOf.set(s.no, wrapDisplayText(s.detail, Math.max(8, cols - displayWidth(detailIndent))).map((l) => `${detailIndent}${ui.dim}${l}${ui.reset}`));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
// 有步骤被裁掉时,末行要留给「… 还有 K 步」指示:先按「全部装得下」试探,
|
|
273
|
+
// 装不下则预扣 1 行给指示,再走一遍裁剪(保证 planRows ≤ cap)。
|
|
274
|
+
let budget = cap - 1;
|
|
275
|
+
const fits = (b) => {
|
|
276
|
+
let left = b;
|
|
277
|
+
const vis = [];
|
|
278
|
+
let hidden = 0;
|
|
279
|
+
for (const s of steps) {
|
|
280
|
+
const need = 1 + (detailOf.get(s.no)?.length ?? 0);
|
|
281
|
+
if (need <= left) {
|
|
282
|
+
vis.push(s);
|
|
283
|
+
left -= need;
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
hidden = steps.length - vis.length;
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return { visible: vis, hidden };
|
|
291
|
+
};
|
|
292
|
+
let { visible, hidden } = fits(budget);
|
|
293
|
+
if (hidden > 0 && visible.length > 0) {
|
|
294
|
+
// 预扣指示行后重裁;若连一个步骤都装不下(极端矮终端),放弃指示行保步骤。
|
|
295
|
+
const retry = fits(budget - 1);
|
|
296
|
+
if (retry.visible.length > 0) {
|
|
297
|
+
visible = retry.visible;
|
|
298
|
+
hidden = retry.hidden;
|
|
299
|
+
budget -= 1;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
for (const s of visible) {
|
|
303
|
+
const mark = s.done ? `${ui.green}✓${ui.reset}` : s.current ? `${ui.accent}▸${ui.reset}` : `${ui.dim}·${ui.reset}`;
|
|
304
|
+
// 前缀 = 缩进2 + 标记1 + 空格1 + "N. "(编号位数 + 2);label 吃掉剩余列,保证整行不 wrap。
|
|
305
|
+
const prefixW = displayWidth(PLAN_STEP_INDENT) + 1 + 1 + String(s.no).length + 2;
|
|
306
|
+
const open = detailOf.has(s.no);
|
|
307
|
+
const hasDetail = s.detail != null && s.detail !== '';
|
|
308
|
+
// 行尾可展开提示:有详情未展开 ▸ / 已展开 ▾(与标题行的箭头语义一致)。
|
|
309
|
+
const endCaret = !hasDetail ? '' : open ? ` ${ui.dim}▾${ui.reset}` : ` ${ui.dim}▸${ui.reset}`;
|
|
310
|
+
const labelW = Math.max(1, cols - prefixW - (hasDetail ? 2 : 0));
|
|
311
|
+
const label = truncateDisplay(s.label, labelW);
|
|
312
|
+
const color = s.done ? ui.dim : s.current ? ui.yellow : ui.dim;
|
|
313
|
+
lines.push(`${PLAN_STEP_INDENT}${mark} ${color}${s.no}. ${label}${ui.reset}${endCaret}`);
|
|
314
|
+
state.planRowStep.push(s.no);
|
|
315
|
+
const d = detailOf.get(s.no);
|
|
316
|
+
if (d) {
|
|
317
|
+
lines.push(...d);
|
|
318
|
+
for (let i = 0; i < d.length; i++)
|
|
319
|
+
state.planRowStep.push(s.no); // 点详情行=再点收起
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
if (hidden > 0) {
|
|
323
|
+
lines.push(`${PLAN_STEP_INDENT}${ui.dim}… ${t('status.planMoreSteps', { count: hidden })}${ui.reset}`);
|
|
324
|
+
state.planRowStep.push(null); // 指示行不可点
|
|
325
|
+
}
|
|
326
|
+
// 极端情况下 steps 为空(数据缺失):只有标题行,仍能点击收起。
|
|
327
|
+
state.planRows = Math.max(1, lines.length);
|
|
328
|
+
return lines;
|
|
329
|
+
}
|
|
330
|
+
/** plan 区域高度变化(展开/收起/结算)后的全幅重排回调,由 core.ts 注入
|
|
331
|
+
* (paintInput 同步重设 DECSTBM + 重画脚栏):statusbar 不能静态 import input-paint(循环依赖),
|
|
332
|
+
* 也不能用动态 import——异步窗口内 80ms 心跳会按新 planRows + 旧 footerH 画错行。 */
|
|
333
|
+
let planRelayout = null;
|
|
334
|
+
export function setPlanRelayoutHandler(fn) {
|
|
335
|
+
planRelayout = fn;
|
|
336
|
+
}
|
|
337
|
+
/** 切换 plan chip 展开/收起(鼠标点击标题行)。无活跃 plan / 无步骤数据时 no-op。
|
|
338
|
+
* 经注入的同步回调重设区域并重画整个脚栏;回调缺失时退化为 drawStatusBar。
|
|
339
|
+
* 收起时保留 planOpenSteps(重新展开还原各步详情展开状态),换计划才清空。 */
|
|
340
|
+
export function togglePlanExpanded() {
|
|
341
|
+
if (!state.active || !state.base?.planSummary)
|
|
342
|
+
return;
|
|
343
|
+
if (!state.planExpanded && !(state.base.planSteps && state.base.planSteps.length > 0))
|
|
344
|
+
return;
|
|
345
|
+
state.planExpanded = !state.planExpanded;
|
|
346
|
+
if (state.lastView && planRelayout)
|
|
347
|
+
planRelayout();
|
|
348
|
+
else
|
|
349
|
+
drawStatusBar();
|
|
350
|
+
}
|
|
351
|
+
/** 切换单个步骤的详情展开/收起(鼠标点击步骤行/详情行)。无详情数据时 no-op。 */
|
|
352
|
+
export function togglePlanDetail(stepNo) {
|
|
353
|
+
if (!state.active || !state.planExpanded)
|
|
354
|
+
return;
|
|
355
|
+
const step = state.base?.planSteps?.find((s) => s.no === stepNo);
|
|
356
|
+
if (!step?.detail)
|
|
357
|
+
return; // 无详情可看,点了也不给反应
|
|
358
|
+
if (state.planOpenSteps.has(stepNo))
|
|
359
|
+
state.planOpenSteps.delete(stepNo);
|
|
360
|
+
else
|
|
361
|
+
state.planOpenSteps.add(stepNo);
|
|
362
|
+
if (state.lastView && planRelayout)
|
|
363
|
+
planRelayout();
|
|
364
|
+
else
|
|
365
|
+
drawStatusBar();
|
|
196
366
|
}
|
|
197
|
-
/** 画状态行(plan 行 + spinner 行 + model
|
|
198
|
-
* 行号(footerH=
|
|
199
|
-
* plan 行
|
|
200
|
-
* plan 第 2 行 = contentBottom+2 (双行,可选)
|
|
367
|
+
/** 画状态行(plan 行 + spinner 行 + model 行)。RUNNING 态 spinner 频繁调。
|
|
368
|
+
* 行号(footerH=5+inputRows+planRows-1):
|
|
369
|
+
* plan 行 1..N = contentBottom+1 .. +planRows (折叠 1 行;展开 = 标题 + 步骤行)
|
|
201
370
|
* spinner 行 = contentBottom+1+planRows (● 空闲 / ⠹ 思考中… / etc)
|
|
202
371
|
* 上线 = contentBottom+2+planRows (画在 paintInput)
|
|
203
372
|
* 输入行 = contentBottom+3+planRows
|
|
@@ -209,20 +378,29 @@ export function drawStatusBar(status) {
|
|
|
209
378
|
// 覆盖层(composer)打开中照常刷底栏:弹窗只占内容区(2..contentBottom-1),底栏行在其外不冲突;
|
|
210
379
|
// 仅末尾光标归位改为弹窗自报位(见下),防 80ms 心跳把弹窗光标拽到底栏输入框。
|
|
211
380
|
const s = status ?? { ...state.base, status: state.statusText, spinnerFrame: state.spinnerFrame };
|
|
381
|
+
const g0 = getGeo();
|
|
382
|
+
const planLines = composePlanLines(s, g0.cols);
|
|
383
|
+
// planRows 与当前 footerH 不符(plan 在运行中被结算/换新,composePlanLines 自动收起展开态等):
|
|
384
|
+
// 心跳路径不会走 paintInput 的 setRegion,这里重设区域并交回调全幅重排(含被吃掉/归还的内容末行),
|
|
385
|
+
// 不能只画 spinner/model——旧上分隔线、输入行会残留在新行位。
|
|
386
|
+
const needFooterH = 5 + state.inputRows + (state.planRows - 1);
|
|
387
|
+
if (needFooterH !== g0.footerH) {
|
|
388
|
+
setRegion(needFooterH);
|
|
389
|
+
planRelayout?.();
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
212
392
|
const g = getGeo();
|
|
213
|
-
const planLines = composePlanLines(s, g.cols);
|
|
214
393
|
const planRow1 = g.contentBottom + 1;
|
|
215
394
|
const spinnerRow = g.contentBottom + 1 + state.planRows;
|
|
216
395
|
const modelRow = g.rows; // 屏底:model 行
|
|
217
|
-
// plan
|
|
218
|
-
// 一次写入:plan 1/2 行 + spinner 行 + model 行,末尾 cup 回续写位/输入框光标。
|
|
396
|
+
// 一次写入:plan 各行 + spinner 行 + model 行,末尾 cup 回续写位/输入框光标。
|
|
219
397
|
let planBuf = '';
|
|
220
398
|
for (let i = 0; i < planLines.length; i++) {
|
|
221
399
|
planBuf += cup(planRow1 + i, 1) + esc.clearLine + planLines[i];
|
|
222
400
|
}
|
|
223
|
-
//
|
|
224
|
-
|
|
225
|
-
planBuf += cup(
|
|
401
|
+
// 上轮 plan 占的行数比本轮多(步骤变少,展开态被钳短):清掉本轮不再使用的残留行,不留尾巴。
|
|
402
|
+
for (let r = planRow1 + planLines.length; r < spinnerRow; r++) {
|
|
403
|
+
planBuf += cup(r, 1) + esc.clearLine;
|
|
226
404
|
}
|
|
227
405
|
// plan 从非空变成空(已结算为 ## Done:/ notes 里无活跃 ## Plan: 段)时,清掉残留的 plan 行 1。
|
|
228
406
|
// 否则上轮渲染的「plan: 标题 (N/M) ▸ 当前步」会卡在底栏「虚拟空行」位置直到下一次重启 REPL。
|
package/dist/ui/layout-types.js
CHANGED