mocode-ai 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.js +18 -7
- package/dist/agent/mentioned-files.js +71 -0
- package/dist/agent/model-turn.js +68 -30
- package/dist/agent/progress-guard.js +67 -0
- package/dist/agent/run-coordinator.js +155 -24
- package/dist/agent/short-path-completion.js +109 -0
- package/dist/agent/spawn.js +43 -0
- package/dist/agent/stages/history-manager.js +1 -0
- package/dist/agent/stages/tool-dispatcher.js +6 -3
- package/dist/agent/tool-helpers.js +2 -2
- package/dist/agent/tool-turn.js +49 -4
- package/dist/agent/work-discipline.js +12 -9
- package/dist/changeset/index.js +2 -1
- package/dist/config/index.js +12 -10
- package/dist/context/overlapping-reads.js +66 -0
- package/dist/context/relevance.js +11 -2
- package/dist/context/usage-snapshot.js +9 -6
- package/dist/host/stdio.js +96 -42
- package/dist/i18n/index.js +26 -10
- package/dist/llm/index.js +27 -3
- package/dist/llm/message-shape.js +18 -0
- package/dist/llm/reasoning.js +17 -0
- package/dist/memory/index.js +1 -1
- package/dist/memory/tail.js +9 -26
- package/dist/models/reasoning-cap.js +19 -2
- package/dist/orchestrator/lane-executor.js +7 -1
- package/dist/orchestrator/repl.js +30 -49
- package/dist/repl/commands/appearance.js +1 -2
- package/dist/repl/commands/compact.js +4 -0
- package/dist/repl/commands/model-actions.js +4 -3
- package/dist/repl/commands/model.js +2 -3
- package/dist/repl/message-format.js +7 -6
- package/dist/repl/running-input.js +27 -65
- package/dist/repl/runtime.js +119 -77
- package/dist/rollback/index.js +2 -2
- package/dist/rollback/store.js +73 -38
- package/dist/runtime/runtime.js +1 -1
- package/dist/session/compact.js +41 -4
- package/dist/session/retention.js +4 -0
- package/dist/session/short-path-metrics.js +185 -0
- package/dist/session/store.js +78 -3
- package/dist/session/terminal-transcript.js +101 -0
- package/dist/tools/builtins/ask-human.js +2 -2
- package/dist/tools/builtins/edit-file.js +79 -19
- package/dist/tools/builtins/grep.js +161 -42
- package/dist/tools/builtins/plan-update.js +4 -2
- package/dist/tools/builtins/read-file.js +148 -55
- package/dist/tools/builtins/run-command.js +57 -9
- package/dist/tools/ripgrep-client.js +72 -26
- package/dist/tools/tool-runtime.js +29 -8
- package/dist/ui/layout-internal/content-write.js +7 -3
- package/dist/ui/layout-internal/core.js +1 -1
- package/dist/ui/layout-internal/state.js +0 -6
- package/dist/ui/layout-internal/statusbar.js +0 -30
- package/dist/ui/output-sink.js +24 -0
- package/dist/ui/render.js +3 -0
- package/dist/ui/spinner.js +3 -1
- package/dist/verification/evidence.js +52 -0
- package/package.json +4 -2
package/dist/agent/tool-turn.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { isToolResultsNoise } from './tool-helpers.js';
|
|
1
|
+
import { isToolResultsNoise, parseArgs } from './tool-helpers.js';
|
|
2
|
+
import { t } from '../i18n/index.js';
|
|
2
3
|
const PLAN_NAG_THRESHOLD = 3;
|
|
3
4
|
const PLAN_NAG_TEXT = '[mocode] Reminder: you have an active plan in notes.md but have not updated it recently. ' +
|
|
4
5
|
'If you finished a step, call plan_update to check it off (keep at most one in_progress); ' +
|
|
@@ -9,9 +10,36 @@ const PLAN_NAG_TEXT = '[mocode] Reminder: you have an active plan in notes.md bu
|
|
|
9
10
|
* 新增附件产出点**必须**复用这一个前言。
|
|
10
11
|
*/
|
|
11
12
|
export const ATTACHMENT_PREAMBLE = 'The read_file tool loaded the following visual input: ';
|
|
13
|
+
function describeFirstAction(call) {
|
|
14
|
+
switch (call.name) {
|
|
15
|
+
case 'read_file':
|
|
16
|
+
case 'edit_file':
|
|
17
|
+
case 'write_file': {
|
|
18
|
+
const path = parseArgs(call.arguments)?.path;
|
|
19
|
+
const file = typeof path === 'string' && path.trim() && !/[\p{Cc}\p{Cf}]/u.test(path)
|
|
20
|
+
? JSON.stringify(path.length > 100 ? path.slice(0, 97) + '…' : path)
|
|
21
|
+
: t('agent.openingTargetFile');
|
|
22
|
+
return t(call.name === 'read_file' ? 'agent.openingRead' : 'agent.openingEdit', { file });
|
|
23
|
+
}
|
|
24
|
+
case 'grep':
|
|
25
|
+
case 'glob':
|
|
26
|
+
return t('agent.openingSearch');
|
|
27
|
+
case 'run_command':
|
|
28
|
+
return t('agent.openingCommand');
|
|
29
|
+
case 'web_search':
|
|
30
|
+
case 'web_fetch':
|
|
31
|
+
return t('agent.openingWeb');
|
|
32
|
+
case 'ask_human':
|
|
33
|
+
return t('agent.openingClarify');
|
|
34
|
+
case 'add_tool_groups':
|
|
35
|
+
return t('agent.openingTools');
|
|
36
|
+
default:
|
|
37
|
+
return t('agent.openingGeneric');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
12
40
|
/** Owns tool-turn history publication, transaction settlement, plan nag, attachments and checkpoint ordering. */
|
|
13
41
|
export async function runToolTurn(input) {
|
|
14
|
-
const { opts, ctx, historyManager, result, stream, step, maxSteps, planState, turnLifecycle, cancellationLifecycle, terminationPolicy, rebuildHistoryIndexes, dispatch, } = input;
|
|
42
|
+
const { opts, ctx, historyManager, result, stream, step, opening, maxSteps, planState, turnLifecycle, cancellationLifecycle, terminationPolicy, rebuildHistoryIndexes, dispatch, } = input;
|
|
15
43
|
const { hooks, signal } = opts;
|
|
16
44
|
turnLifecycle.addToolCalls(result.toolCalls.length);
|
|
17
45
|
if (result.content && isToolResultsNoise(result.content)) {
|
|
@@ -20,9 +48,26 @@ export async function runToolTurn(input) {
|
|
|
20
48
|
stream.gotText = false;
|
|
21
49
|
stream.lastChar = '';
|
|
22
50
|
}
|
|
23
|
-
|
|
51
|
+
const needsOpening = opening && (!stream.gotText || !result.content?.trim());
|
|
52
|
+
if (needsOpening) {
|
|
53
|
+
// UI 兜底只陈述已知动作,不伪造模型正文或把工具参数写进模型历史。
|
|
54
|
+
const call = result.toolCalls[0];
|
|
55
|
+
const action = describeFirstAction(call);
|
|
56
|
+
hooks.onText?.(opening === 'steering' ? t('agent.openingSteered', { action }) : action);
|
|
57
|
+
turnLifecycle.emitTrace('opening_fallback', { tool: call.name, ...(opening === 'steering' ? { opening } : {}) });
|
|
58
|
+
}
|
|
59
|
+
if (needsOpening || (stream.mode !== 'idle' && stream.lastChar !== '\n'))
|
|
24
60
|
hooks.onTextEnd?.();
|
|
25
|
-
|
|
61
|
+
if (opening) {
|
|
62
|
+
for (const call of result.toolCalls)
|
|
63
|
+
hooks.onToolCall?.(call.name);
|
|
64
|
+
hooks.onChatDone?.();
|
|
65
|
+
}
|
|
66
|
+
historyManager.appendAssistantTurn({
|
|
67
|
+
content: result.content,
|
|
68
|
+
toolCalls: result.toolCalls,
|
|
69
|
+
reasoningContent: result.reasoningContent,
|
|
70
|
+
});
|
|
26
71
|
const toolBatch = historyManager.beginToolBatch(result.toolCalls);
|
|
27
72
|
const workingHistory = toolBatch.workingMessages;
|
|
28
73
|
try {
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
// Lightweight, advisory working guidance. The agent decides how much discovery and
|
|
2
2
|
// validation each task needs; the framework does not enforce a completion gate.
|
|
3
|
+
export const PLAN_USAGE_GUIDANCE = 'For tool-using work, call `plan_update` before broad investigation or implementation when the user requests a plan, ' +
|
|
4
|
+
'the task has distinct deliverables or at least three substantive phases, crosses components with separate checks, risks context loss, or needs a durable handoff. ' +
|
|
5
|
+
'If a focused check reveals that the task meets these criteria, create or update the plan before continuing. Reuse a plan that already fits the task. ' +
|
|
6
|
+
'Locating, editing and checking one focused change count as one phase.';
|
|
3
7
|
/**
|
|
4
8
|
* 从 config.model 字符串里嗅探 model family。匹配规则尽量宽松,够用即可。
|
|
5
9
|
* 未来 AHE 闭环后可以换成 config.modelFamily 字段。
|
|
@@ -23,26 +27,25 @@ export function inferModelFamily(model) {
|
|
|
23
27
|
const CORE_SECTION = `Use your judgment to choose the shortest reliable path from the request to a useful result.
|
|
24
28
|
|
|
25
29
|
- Answer directly when you already can: questions, explanations, advice, reviews, and read-only analysis that the conversation and known evidence already support get a direct answer with no tools, no extra investigation, and no validation. Reach for a tool only when the answer genuinely depends on information you do not have.
|
|
26
|
-
-
|
|
30
|
+
- For one focused change in AUTO, read the owning code, apply the edit as soon as its target and effect are clear, and review the returned change. Open another file only to resolve a concrete dependency. Check changed behavior at its entry point when it could regress, then report the result.
|
|
27
31
|
- Make the smallest coherent change and avoid unrelated refactors.
|
|
28
32
|
- Preserve existing behavior and public API compatibility unless the task explicitly requires a change.
|
|
29
|
-
-
|
|
30
|
-
- When validation is useful,
|
|
31
|
-
- Re-read or rerun
|
|
33
|
+
- Review the diff returned by edit_file when available. For small local edits such as a label or style tweak, that can be sufficient. For a logic change, pick the smallest check that exercises the requested behavior. Respect explicit acceptance checks.
|
|
34
|
+
- When validation is useful, run ONE smallest relevant check, once: the owning package's typecheck, a single targeted test, or the affected entry point. Do not chain typecheck → lint → build → test, do not re-run a check that already passed on code you have not touched since, and do not run broad suites "to be safe". Comments, docs, formatting, and typo fixes need no check at all. It is optional, not a completion gate.
|
|
35
|
+
- Use the evidence already gathered. Make another call when it can resolve a remaining decision or verify a requested outcome. Once the outcomes are established, finish. Re-read or rerun when state may have changed or an edit needs exact current content.
|
|
32
36
|
- On failure, diagnose before retrying; after repeated identical failures, change approach.
|
|
33
37
|
- Report honestly what you changed, what you checked, and anything left uncertain.
|
|
34
38
|
|
|
35
39
|
Never invent file paths, APIs, config keys, flags, or behavior. Distinguish repository evidence from assumptions.`;
|
|
36
40
|
/**
|
|
37
|
-
*
|
|
38
|
-
* The agent must call `ask_human` BEFORE acting; only trivial, reversible details may be decided alone.
|
|
41
|
+
* 用户决定影响结果的取舍与关键变更;常规、可回退的实现细节由 agent 处理。
|
|
39
42
|
*/
|
|
40
43
|
const ASK_WHITELIST_SECTION = `## When to ask instead of guess
|
|
41
44
|
|
|
42
|
-
|
|
45
|
+
Carry out a clear request using established local conventions. Choose routine, reversible implementation details yourself. Use \`ask_human\` before a key modification or when a missing user decision would change the outcome.
|
|
43
46
|
|
|
44
47
|
Ask BEFORE acting when any of these applies:
|
|
45
|
-
1. A decision point:
|
|
48
|
+
1. A decision point: the available choices materially change user-visible behavior, compatibility, cost, or scope and the user has not chosen. Present the options with trade-offs and your recommendation.
|
|
46
49
|
2. A key modification: changing public APIs, data formats, schemas, config semantics, or default behavior; adding, removing, or upgrading dependencies; renaming/moving/deleting files or modules; changing architecture or cross-module contracts; touching auth, permissions, security, or build/CI/release setup.
|
|
47
50
|
3. A broad or risky change: edits spanning many files, large refactors, anything hard to reverse, or any external side effect (push, deploy, network writes, data deletion/migration).
|
|
48
51
|
4. Scope growth: the work needs more than what the user asked for (extra features, unrelated fixes, behavior changes), or the request admits two or more materially different readings.
|
|
@@ -53,7 +56,7 @@ For ambiguous or vague requests, load the \`brainstorming\` skill and clarify th
|
|
|
53
56
|
|
|
54
57
|
If the user cancels or answers "you decide", stop guessing: take the safest reversible option and state it. Do not repeat a question the user already answered.
|
|
55
58
|
|
|
56
|
-
|
|
59
|
+
An explicit request to implement a focused change authorizes its ordinary local implementation choices. Disclose assumptions that affect the result.
|
|
57
60
|
|
|
58
61
|
There is no per-turn cap on \`ask_human\`: ask as often as a decision genuinely requires, but batch related questions into one call instead of asking one trivial thing at a time. If \`ask_human\` is unavailable or no user can answer (non-interactive run), choose the safest reversible option, avoid the key modification if possible, and disclose it in the final reply.`;
|
|
59
62
|
/** Advisory guidance shared by main and sub-agents. */
|
package/dist/changeset/index.js
CHANGED
|
@@ -175,7 +175,8 @@ export async function commitChangeSet(changeSet, signal) {
|
|
|
175
175
|
}
|
|
176
176
|
const captures = effective.map((change) => ({
|
|
177
177
|
change,
|
|
178
|
-
|
|
178
|
+
// dry-run 已读取原文。首次替换前仍会逐路径复核 hash,复核失败时整批不落回滚快照。
|
|
179
|
+
capture: beginPathMutation(change.absolutePath, change.before ?? undefined),
|
|
179
180
|
}));
|
|
180
181
|
const createdDirectories = new Set();
|
|
181
182
|
const tempByPath = new Map();
|
package/dist/config/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import { getActiveSkill } from '../skills/activation.js';
|
|
|
7
7
|
import { getCurrentSessionId } from '../session/state.js';
|
|
8
8
|
import { getNotesFilePath, extractActiveNotesSections } from '../session/notes.js';
|
|
9
9
|
import { buildGuiActionsSection } from '../session/gui-actions.js';
|
|
10
|
-
import { buildWorkDisciplineSection, inferModelFamily } from '../agent/work-discipline.js';
|
|
10
|
+
import { buildWorkDisciplineSection, inferModelFamily, PLAN_USAGE_GUIDANCE } from '../agent/work-discipline.js';
|
|
11
11
|
import { buildValidationCommandsSection } from '../verification/prompt.js';
|
|
12
12
|
import { getActivePresetName, readPreset } from './presets.js';
|
|
13
13
|
import { detectLanguage, setLanguage, t } from '../i18n/index.js';
|
|
@@ -144,7 +144,7 @@ const DEFAULT_VOICE = `## Voice
|
|
|
144
144
|
- Give technical recommendations with brief trade-off reasoning when choices exist.
|
|
145
145
|
- Focus on useful information. Avoid unnecessary greetings, apologies, repetition, or filler.
|
|
146
146
|
- Match the user's style and language while staying task-focused.
|
|
147
|
-
- Disclose assumptions
|
|
147
|
+
- Disclose material assumptions and ask about decisions that affect the outcome (see When to ask instead of guess).`;
|
|
148
148
|
/** 解析用户自定义声音:persona.md 文件优先(项目级 > 全局),其次 env MOCODE_PERSONA。无则返回 ''。 */
|
|
149
149
|
function readPersonaFile() {
|
|
150
150
|
const candidates = [
|
|
@@ -471,7 +471,7 @@ Complete programming tasks through an "analyze → call tool → observe result
|
|
|
471
471
|
## Workflow
|
|
472
472
|
- Answer first: if the request is a question, explanation, or read-only analysis you can already answer from context and known evidence, reply directly — no tools, no exploration, no verification ceremony. Tool calls and checks exist only to get information the answer actually needs.
|
|
473
473
|
- Understand: use existing conversation and tool evidence before gathering more.
|
|
474
|
-
- Plan:
|
|
474
|
+
- Plan: ${PLAN_USAGE_GUIDANCE}
|
|
475
475
|
- Delegate: when the \`sub-agent\` tool is exposed, prefer it for exploration-heavy work (unfamiliar subsystems, multi-file audits, open-ended "how does X work here" investigation) and for independent sub-tasks — emit several \`sub-agent\` calls in ONE message and they run concurrently. A worker returns only its summary, so its tool noise never floods the main context. Keep single known-path reads and trivial lookups inline.
|
|
476
476
|
- Implement: edit against a fresh read (see Tool policy); change scope follows Engineering principles.
|
|
477
477
|
- Verify: only for work that changes code or behavior, and only when the risk is worth it — pure answers and read-only analysis need no verification. Whether and what to run follows Engineering principles; use Validation commands for exact commands.
|
|
@@ -484,13 +484,14 @@ ${buildValidationCommandsSection()}
|
|
|
484
484
|
${buildWorkDisciplineSection(inferModelFamily(config.model))}
|
|
485
485
|
|
|
486
486
|
## Tool policy
|
|
487
|
-
-
|
|
488
|
-
-
|
|
489
|
-
- Edit against a FRESH read: before editing, call read_file on the exact path and copy the exact target text. Never reconstruct old_string from a grep/summary/diff — those lose whitespace and indentation and cause edit failures.
|
|
487
|
+
- Read the named file first. For a local edit with a known line, use read_file with offset and about 40 lines of context. With exact target text, anchor to it or a nearby line and set a small limit. If only the declaration is known, use it as the anchor and read enough of the implementation to find the edit. Read a wider range when the task spans multiple blocks. Use narrow grep to discover unknown paths.
|
|
488
|
+
- Edit against fresh exact text. For an unknown file and a specific symbol or literal, use grep(edit_context=true, max_edit_candidates=3). If an [edit_context ...] excerpt covers the change, choose the path that matches the user’s intent, copy the exact text and pass that file’s hash as expected_hash to edit_file without rereading. Otherwise use read_file on the exact path and narrow range. Ordinary search hits, summaries and diffs are not edit evidence.
|
|
490
489
|
- Pick the right file tool: for an EXISTING file, DEFAULT to edit_file — one old_string for a single change, replacements[] for many separate changes in one atomic call, or a line range for a big block. Do NOT overwrite an existing file with write_file just to tweak parts of it (re-sending the whole file wastes tokens and its long JSON is truncation-prone). Use write_file only to create a new file, to append (append=true needs no read_file and no hash), or to rewrite essentially the WHOLE file (a full rewrite needs the latest read_file hash). expected_hash is OPTIONAL in edit_file old_string/replacements mode, REQUIRED in line-range mode. Never write a throwaway script (tmp_patch*.cjs, fix_*.py, ...) to modify source files: scripts run outside ChangeSet tracking, so rollback and diff cannot see them.
|
|
491
|
-
-
|
|
490
|
+
- Treat evidence from before compaction, session resume, an edit conflict, or an external change as stale. Reread the affected range before reusing its text or hash. In old_string mode with a fresh read_file, expected_hash is optional.
|
|
492
491
|
- Emit multiple independent tool calls in ONE assistant message so they run concurrently — e.g. several read_file regions, a grep plus a glob, or several web_fetch calls. One lookup per message wastes a full model round-trip each time. Place parallel-safe calls consecutively; keep any call that depends on their results (e.g. an edit) for the next message.
|
|
493
492
|
- Never batch a read with an edit that depends on it; do not repeat overlapping reads or unchanged failed calls.
|
|
493
|
+
- Batch related verification checks that share setup into one bounded script or existing test command. Return a compact per-check result and failure samples, without credentials or full response bodies. Use dedicated file tools for source lookup.
|
|
494
|
+
- When a group of checks fails in the same way, inspect the shared dependency once (for example, gateway registration when several related API paths return 404). Record confirmed blockers, finish independent checks, and batch the affected rechecks after any authorized fix. Report once the requested checks have evidence or a concrete blocker.
|
|
494
495
|
- On failure, inspect the full error, change the approach, and retry only with a reason. Drop stale tool output when it no longer supports the task.
|
|
495
496
|
- For generated content over roughly 200 lines or 5K tokens, write it in stages: first write_file the initial chunk, then extend it with write_file(append=true, content=<next chunk>) — each call stays small and the file grows transactionally. Appends are VERBATIM: if the file does not already end with a newline, begin your chunk with "\\n" so lines do not merge.
|
|
496
497
|
|
|
@@ -505,7 +506,7 @@ ${buildVoiceSection()}
|
|
|
505
506
|
|
|
506
507
|
## Reporting
|
|
507
508
|
- Stop immediately when no more tools are needed; give conclusions directly.
|
|
508
|
-
- **Do not stop prematurely during exploration**:
|
|
509
|
+
- **Do not stop prematurely during exploration**: once you are already gathering evidence for a task, keep calling tools until you have enough to answer — do not bail out mid-investigation. This applies to the task you decided to work on, not to deciding whether a tool was needed at all: if the request was a question you could already answer, answering it directly was complete. Only stop when you have sufficient evidence or hit a dead end.
|
|
509
510
|
- **No flattery / no preamble in conclusions**: skip "Sure", "好的", "我已经完成了" and similar no-information prefixes — jump straight to substance.
|
|
510
511
|
- **Lead with the outcome**: the first line says what you did or what you found in one sentence — no restatement of the request, no "task completed" wrapper.
|
|
511
512
|
- **Shape the rest for scanning**, including only the sections that carry content: what changed (grouped by logical change: \`path:line\` plus the behavior it delivers, one line each; note renames/deletions; skip purely mechanical edits) → what you verified and its result, or "not run" with the reason → what is still open (≤3 bullets). Never paste diffs or whole files the terminal already showed.
|
|
@@ -513,7 +514,7 @@ ${buildVoiceSection()}
|
|
|
513
514
|
- **Prevent the follow-up**: before you stop, check the reply already answers what the user would ask next — what changed and where, why, what you verified, and what is left or uncertain. A missing fact costs the user a whole extra round-trip; add that fact, not more prose.
|
|
514
515
|
- **No dead endings**: drop "hope this helps", "if you need anything else…", "let me know if you'd like me to…", and any closing paragraph that restates what you just wrote.
|
|
515
516
|
- **Terminal-first formatting**: at most one level of \`##\` headings or a few bold lead-ins, lists no deeper than two levels, tables only when a column comparison is what makes them readable, no emoji. Reply in the user's language; keep code, paths, and commands verbatim.
|
|
516
|
-
- Definition of done (code/behavior changes only): never declare a multi-feature implementation finished just because the code exists.
|
|
517
|
+
- Definition of done (multi-feature code/behavior changes only): never declare a multi-feature implementation finished just because the code exists. Where the change is actually observable to a check, verify it — one relevant check run, or the affected entry point exercised — not a chain of them. For a focused edit, follow the risk-based check in Engineering principles. Mark plan steps \`[x]\` once the step's work is complete, not only after a command ran. If the user supplied an acceptance list, every item on it must pass. Unverified items belong in the reply as pending, not folded into "done". This rule does not apply to questions, explanations, or read-only analysis.`;
|
|
517
518
|
// 动态段(置于末尾):AGENTS.md 项目记忆 + notepad 索引/说明。工具簇特定指导由
|
|
518
519
|
// ToolPolicyController.reminder() 按当前 turn 的 route 注入,避免旧全局 profile 与真实 schema 分裂。
|
|
519
520
|
// 按需注入(#13):有内容的索引才拼对应标题,避免空标题噪声。
|
|
@@ -523,7 +524,7 @@ ${buildVoiceSection()}
|
|
|
523
524
|
// 避免把规则在系统提示里每请求预付第三遍。**标题 '## Session state' 必须保留**:
|
|
524
525
|
// buildMocodeCorePrompt 靠 MARKER_DROPPABLE_SECTION 给子 agent 切片。
|
|
525
526
|
dynamicParts.push(`## Session state (\`.mocode/sessions/${sessionId ?? '<id>'}/notes.md\`)\n` +
|
|
526
|
-
'
|
|
527
|
+
'Use `plan_update` for durable plans and `note_append` for non-obvious findings, decisions or risks. ' +
|
|
527
528
|
'Both write notes.md, which survives compaction — run read_file on it to recover context after compaction. ' +
|
|
528
529
|
'Their formats and rules live in each tool\u2019s description; do not hand-edit the files. ' +
|
|
529
530
|
'When compaction drops older conversation, its verbatim text (user messages, your earlier decisions, full tool args/results) is archived under ' +
|
|
@@ -612,6 +613,7 @@ export const config = {
|
|
|
612
613
|
: (__activePreset?.reasoningEffort ?? parseReasoningEffort(process.env.REASONING_EFFORT) ?? 'auto'),
|
|
613
614
|
compactFork: process.env.MOCODE_COMPACT_FORK !== 'false',
|
|
614
615
|
readDedup: process.env.MOCODE_READ_DEDUP !== 'false',
|
|
616
|
+
shortPathCompletion: process.env.MOCODE_SHORT_PATH_COMPLETION === 'true',
|
|
615
617
|
contextOptimize: process.env.MOCODE_CONTEXT_OPTIMIZE !== 'false',
|
|
616
618
|
contextRelprune: process.env.MOCODE_CONTEXT_RELPRUNE !== 'false',
|
|
617
619
|
contextLifecycle: process.env.MOCODE_LIFECYCLE !== 'false',
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
const READ_HEADER = /^\[artifact source=read_file path=.+ hash=sha256:[a-f0-9]{64}\]$/;
|
|
2
|
+
const NUMBERED_LINE = /^ *([1-9]\d*)\t/;
|
|
3
|
+
const MIN_RESULT_CHARS = 4_000;
|
|
4
|
+
const MIN_SAVED_CHARS = 800;
|
|
5
|
+
/** 从实际会发出的同轮工具结果中复用原文。持久化历史和工具界面仍持有完整结果。 */
|
|
6
|
+
export function compactOverlappingReads(history) {
|
|
7
|
+
const earlierVersions = new Map();
|
|
8
|
+
let result = history;
|
|
9
|
+
for (let i = 0; i < history.length; i++) {
|
|
10
|
+
const message = history[i];
|
|
11
|
+
if (message.role === 'user')
|
|
12
|
+
earlierVersions.clear();
|
|
13
|
+
if (message.role !== 'tool' || typeof message.content !== 'string')
|
|
14
|
+
continue;
|
|
15
|
+
const content = message.content;
|
|
16
|
+
const headerEnd = content.indexOf('\n');
|
|
17
|
+
if (headerEnd < 0 || !READ_HEADER.test(content.slice(0, headerEnd)))
|
|
18
|
+
continue;
|
|
19
|
+
if (content.includes('…[已截断'))
|
|
20
|
+
continue;
|
|
21
|
+
const header = content.slice(0, headerEnd);
|
|
22
|
+
const previous = earlierVersions.get(header);
|
|
23
|
+
if (previous === undefined) {
|
|
24
|
+
earlierVersions.set(header, content);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const prior = typeof previous === 'string'
|
|
28
|
+
? new Set(previous.split('\n').filter((line) => NUMBERED_LINE.test(line)))
|
|
29
|
+
: previous;
|
|
30
|
+
earlierVersions.set(header, prior);
|
|
31
|
+
const output = [header];
|
|
32
|
+
let start = 0;
|
|
33
|
+
let end = 0;
|
|
34
|
+
const flush = () => {
|
|
35
|
+
if (!start)
|
|
36
|
+
return;
|
|
37
|
+
output.push(`[Lines ${start}–${end} already shown above for this file version.]`);
|
|
38
|
+
start = 0;
|
|
39
|
+
};
|
|
40
|
+
for (const line of content.slice(headerEnd + 1).split('\n')) {
|
|
41
|
+
const match = NUMBERED_LINE.exec(line);
|
|
42
|
+
const number = Number(match?.[1]);
|
|
43
|
+
if (match && content.length >= MIN_RESULT_CHARS && prior.has(line)) {
|
|
44
|
+
if (start && number !== end + 1)
|
|
45
|
+
flush();
|
|
46
|
+
if (!start)
|
|
47
|
+
start = number;
|
|
48
|
+
end = number;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
flush();
|
|
52
|
+
output.push(line);
|
|
53
|
+
}
|
|
54
|
+
if (match)
|
|
55
|
+
prior.add(line);
|
|
56
|
+
}
|
|
57
|
+
flush();
|
|
58
|
+
const compacted = output.join('\n');
|
|
59
|
+
if (content.length - compacted.length < MIN_SAVED_CHARS)
|
|
60
|
+
continue;
|
|
61
|
+
if (result === history)
|
|
62
|
+
result = history.slice();
|
|
63
|
+
result[i] = { ...message, content: compacted };
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
@@ -28,7 +28,8 @@ function normalizedInteger(value, fallback) {
|
|
|
28
28
|
* 无法解析参数时返 null(调用方保守跳过,不做区间淘汰)。 */
|
|
29
29
|
function readRange(argsRaw) {
|
|
30
30
|
const args = parseArgs(argsRaw);
|
|
31
|
-
|
|
31
|
+
// 带 anchor 时 offset 是查找起点,实际返回区间取决于文件内容。
|
|
32
|
+
if (!args || args.anchor !== undefined)
|
|
32
33
|
return null;
|
|
33
34
|
const offset = Math.max(1, normalizedInteger(args.offset, 1));
|
|
34
35
|
const limit = Math.max(1, Math.min(normalizedInteger(args.limit, READ_DEFAULT_LIMIT), READ_LIMIT_CAP));
|
|
@@ -47,7 +48,15 @@ function observationKey(call) {
|
|
|
47
48
|
tool: 'grep',
|
|
48
49
|
pattern: args.pattern,
|
|
49
50
|
glob: typeof args.glob === 'string' ? args.glob : '**/*',
|
|
50
|
-
|
|
51
|
+
...(args.mode === 'files'
|
|
52
|
+
? { mode: 'files' }
|
|
53
|
+
: {
|
|
54
|
+
mode: 'matches',
|
|
55
|
+
maxPerFile: Math.min(Math.max(rawMax, 1), 50),
|
|
56
|
+
context: Math.min(Math.max(normalizedInteger(args.context, 0), 0), 10),
|
|
57
|
+
editContext: args.edit_context === true,
|
|
58
|
+
maxEditCandidates: normalizedInteger(args.max_edit_candidates, 1),
|
|
59
|
+
}),
|
|
51
60
|
});
|
|
52
61
|
}
|
|
53
62
|
return null;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { chatTools, correctTokenEstimate, estimateMessagesTokens, estimateToolSchemaTokens, estimateTokens, } from '../llm/index.js';
|
|
2
|
+
import { compactOverlappingReads } from './overlapping-reads.js';
|
|
2
3
|
/**
|
|
3
4
|
* 与终端底栏、上下文压力线同口径:system + 对话 + 实际工具 schema + ephemeral。
|
|
4
5
|
* 不能用本轮累计 input+output:后者是消耗量,不是此刻驻留的上下文。
|
|
@@ -11,13 +12,15 @@ export function measureContextUsage(history, contextWindowTokens, contextState)
|
|
|
11
12
|
const activeTools = contextState.activeTools ?? chatTools;
|
|
12
13
|
const ephemeralText = contextState.ephemeralText ?? '';
|
|
13
14
|
const ephemeralRaw = ephemeralText ? estimateTokens(ephemeralText) : 0;
|
|
14
|
-
const
|
|
15
|
+
const historyRaw = estimateMessagesTokens(compactOverlappingReads([...history]));
|
|
16
|
+
const schemaRaw = estimateToolSchemaTokens(activeTools);
|
|
17
|
+
const fullRaw = historyRaw + schemaRaw + ephemeralRaw;
|
|
15
18
|
const anchor = contextState.promptAnchor;
|
|
16
|
-
const
|
|
19
|
+
const anchorPrefixRaw = anchor
|
|
20
|
+
? estimateMessagesTokens(compactOverlappingReads(history.slice(0, anchor.historyLen)))
|
|
21
|
+
: 0;
|
|
17
22
|
const anchorHistoryRaw = anchor
|
|
18
|
-
?
|
|
19
|
-
estimateToolSchemaTokens(activeTools) +
|
|
20
|
-
(anchor.ephemeralText ? estimateTokens(anchor.ephemeralText) : 0)
|
|
23
|
+
? anchorPrefixRaw + schemaRaw + (anchor.ephemeralText ? estimateTokens(anchor.ephemeralText) : 0)
|
|
21
24
|
: 0;
|
|
22
25
|
if (anchor &&
|
|
23
26
|
history.length >= anchor.historyLen &&
|
|
@@ -26,7 +29,7 @@ export function measureContextUsage(history, contextWindowTokens, contextState)
|
|
|
26
29
|
// 同长度替换/原地微压缩也不能沿用旧锚点;历史增长时只比较锚点前缀。
|
|
27
30
|
Math.abs(anchorHistoryRaw - anchor.baseRaw) <= 4 &&
|
|
28
31
|
fullRaw >= anchor.baseRaw - 4) {
|
|
29
|
-
const grownRaw =
|
|
32
|
+
const grownRaw = historyRaw - anchorPrefixRaw;
|
|
30
33
|
tokens = anchor.measuredPromptTokens + Math.max(0, grownRaw);
|
|
31
34
|
// 只有完全同一请求快照才全是实测;后续新增内容仍属于估算。
|
|
32
35
|
source = history.length === anchor.historyLen && fullRaw <= anchor.baseRaw + 4 ? 'measured' : 'estimated';
|
package/dist/host/stdio.js
CHANGED
|
@@ -10,11 +10,12 @@ import { appendCurrentSessionTraceEvent, createContextState, SessionStore, } fro
|
|
|
10
10
|
import { registerWorkspace, readWorkspaceRegistry } from '../workspace/registry.js';
|
|
11
11
|
import { clearSkillActivation } from '../skills/activation.js';
|
|
12
12
|
import { buildSystemMessage } from '../prompt/system-prompt.js';
|
|
13
|
-
import {
|
|
13
|
+
import { buildMemoryTailSnapshot, buildTurnRecallSection, captureMemoryBaseline, gcMemories, initPersona, isTurnRecallEnabled, } from '../memory/index.js';
|
|
14
14
|
import { ToolPolicyController } from '../tools/policy.js';
|
|
15
15
|
import { routeToolGroups } from '../tools/router.js';
|
|
16
16
|
// 装配官方默认工具包:registry 不再顶层 import builtins(破模块循环),host 入口须显式装配。
|
|
17
17
|
import '../tools/builtins/index.js';
|
|
18
|
+
import { muteStdoutOutput } from '../ui/output-sink.js';
|
|
18
19
|
import { setAskHumanHandler } from '../tools/builtins/ask-human.js';
|
|
19
20
|
import { HOST_PROTOCOL_VERSION, parseCommand } from './protocol.js';
|
|
20
21
|
// ── 面板数据源(会话 / 回滚 / 改动 / 用量 / 记忆 / 设置)──
|
|
@@ -39,7 +40,7 @@ let sessionId = '';
|
|
|
39
40
|
let history = [];
|
|
40
41
|
let queryHistory = [];
|
|
41
42
|
let lastToolGroups = [];
|
|
42
|
-
let contextState = createContextState();
|
|
43
|
+
let contextState = createContextState({ archiveHistory: true });
|
|
43
44
|
const approvals = new Map();
|
|
44
45
|
/** 独立 AI 请求按面板 requestId 取消;不得复用任务 run 的 activeRun。 */
|
|
45
46
|
const commitMessageRequests = new Map();
|
|
@@ -177,15 +178,6 @@ function setMode(command) {
|
|
|
177
178
|
}
|
|
178
179
|
emit('mode_changed', { mode: command.mode, previous }, command.id);
|
|
179
180
|
}
|
|
180
|
-
/**
|
|
181
|
-
* R18 每轮静默召回段。开关求与的写法与 REPL 一致(src/agent/index.ts 的 runAgent):
|
|
182
|
-
* 记忆总开关 × 召回子开关。排除 memoryTailChangedIds() —— 那批已由 R17 尾注播报。
|
|
183
|
-
*/
|
|
184
|
-
function turnRecallFor(prompt) {
|
|
185
|
-
if (!isMemoryEnabled() || !isTurnRecallEnabled())
|
|
186
|
-
return '';
|
|
187
|
-
return buildTurnRecallSection(prompt, { excludeIds: memoryTailChangedIds() });
|
|
188
|
-
}
|
|
189
181
|
function createSession() {
|
|
190
182
|
const activeRuntime = runtime();
|
|
191
183
|
sessionId = activeRuntime.session.create();
|
|
@@ -195,7 +187,7 @@ function createSession() {
|
|
|
195
187
|
history = [{ role: 'system', content: currentSystemMessage() }];
|
|
196
188
|
queryHistory = [];
|
|
197
189
|
lastToolGroups = [];
|
|
198
|
-
contextState = createContextState();
|
|
190
|
+
contextState = createContextState({ archiveHistory: true });
|
|
199
191
|
// R17 基线必须跟着「会话真正开始」这一刻拍:/clear、resume 之后旧基线作废,
|
|
200
192
|
// 否则新会话第一条消息会把上一会话的改动当成「本轮新增」播报一遍。
|
|
201
193
|
captureMemoryBaseline();
|
|
@@ -214,7 +206,7 @@ function restoreSession(id) {
|
|
|
214
206
|
history.unshift({ role: 'system', content: currentSystemMessage() });
|
|
215
207
|
queryHistory = [...(loaded.queryHistory ?? [])];
|
|
216
208
|
lastToolGroups = [...(loaded.lastToolGroups ?? [])];
|
|
217
|
-
contextState = createContextState();
|
|
209
|
+
contextState = createContextState({ archiveHistory: true });
|
|
218
210
|
captureMemoryBaseline();
|
|
219
211
|
return true;
|
|
220
212
|
}
|
|
@@ -319,6 +311,31 @@ function hooksFor(runId) {
|
|
|
319
311
|
// usage.totalTokens 是本轮累计消耗,绝不是上下文占用;详情统一读当前 prompt 快照。
|
|
320
312
|
emit('live_usage', { ...usage, contextUsage: contextUsageSnapshot() }, runId);
|
|
321
313
|
},
|
|
314
|
+
// 自动压缩:终端有「压缩中」spinner + 压缩行,GUI 什么都看不到 —— 用户只会发现
|
|
315
|
+
// 上下文百分比莫名掉了一截。所以 start 立刻给状态行,done 在会话流里留一条系统行。
|
|
316
|
+
onCompactProgress: (event) => {
|
|
317
|
+
if (event.phase === 'start') {
|
|
318
|
+
emit('context_compacting', { manual: event.manual, ...(event.focus ? { focus: event.focus } : {}) }, runId);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
// 失败/中断只收状态行:没压成功就不该在会话流里留一条「已压缩」。
|
|
322
|
+
if (event.failed || event.aborted || !event.compacted) {
|
|
323
|
+
emit('context_compacting_done', { failed: event.failed === true, aborted: event.aborted === true }, runId);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const usage = contextUsageSnapshot();
|
|
327
|
+
emit('context_compacted', {
|
|
328
|
+
manual: event.manual,
|
|
329
|
+
summarized: event.summarized,
|
|
330
|
+
reason: event.reason,
|
|
331
|
+
historyRebuilt: event.historyRebuilt === true,
|
|
332
|
+
beforeTokens: event.estimateBefore,
|
|
333
|
+
afterTokens: event.estimateAfter,
|
|
334
|
+
usagePercent: usage.percent,
|
|
335
|
+
contextUsage: usage,
|
|
336
|
+
contextWindow: runtime().context.config.contextWindowTokens,
|
|
337
|
+
}, runId);
|
|
338
|
+
},
|
|
322
339
|
onImageRelief: (info) => emit('image_relief', { ...info }, runId),
|
|
323
340
|
onNoReply: () => emit('no_reply', {}, runId),
|
|
324
341
|
onMaxSteps: () => emit('max_steps', {}, runId),
|
|
@@ -326,11 +343,40 @@ function hooksFor(runId) {
|
|
|
326
343
|
onDone: (elapsedMs, usage) => emit('run_finished', { elapsedMs, usage }, runId),
|
|
327
344
|
};
|
|
328
345
|
}
|
|
346
|
+
function inputForRun(command) {
|
|
347
|
+
return command.attachments?.length
|
|
348
|
+
? [
|
|
349
|
+
...(command.prompt ? [{ type: 'text', text: command.prompt }] : []),
|
|
350
|
+
...command.attachments.flatMap((attachment) => {
|
|
351
|
+
if (attachment.dataUrl)
|
|
352
|
+
return [{ type: 'image_url', name: attachment.name, image_url: { url: attachment.dataUrl } }];
|
|
353
|
+
if (typeof attachment.text !== 'string')
|
|
354
|
+
return [];
|
|
355
|
+
// name/attachment/truncated 是会话回放元数据,transport 发送前统一移除。
|
|
356
|
+
return [
|
|
357
|
+
{
|
|
358
|
+
type: 'text',
|
|
359
|
+
name: attachment.name,
|
|
360
|
+
attachment: true,
|
|
361
|
+
truncated: attachment.truncated === true,
|
|
362
|
+
text: `用户附件 ${JSON.stringify(attachment.name)} 的提取文本如下。${attachment.truncated ? '(内容已截断,仅提供前 100000 字符)' : ''}\n\n${attachment.text}`,
|
|
363
|
+
},
|
|
364
|
+
];
|
|
365
|
+
}),
|
|
366
|
+
]
|
|
367
|
+
: command.prompt;
|
|
368
|
+
}
|
|
329
369
|
async function run(command) {
|
|
330
370
|
if (closing)
|
|
331
371
|
return;
|
|
332
|
-
if (activeRun)
|
|
333
|
-
|
|
372
|
+
if (activeRun) {
|
|
373
|
+
if (activeRun.id !== command.id || activeRun.controller.signal.aborted)
|
|
374
|
+
return error('The active run cannot accept this message.', command.id);
|
|
375
|
+
activeRun.pending.push(inputForRun(command));
|
|
376
|
+
queryHistory.push(command.prompt);
|
|
377
|
+
emit('message_received', { pending: activeRun.pending.length }, command.id);
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
334
380
|
if (!command.prompt.trim() && !command.attachments?.length)
|
|
335
381
|
return;
|
|
336
382
|
let toolPolicy;
|
|
@@ -344,31 +390,11 @@ async function run(command) {
|
|
|
344
390
|
// 每个被接受的 stdio run 都是真实用户 turn;在路由与 Agent 执行前清除上一轮 skill deny。
|
|
345
391
|
clearSkillActivation();
|
|
346
392
|
const controller = new AbortController();
|
|
347
|
-
activeRun = { id: command.id, controller };
|
|
393
|
+
activeRun = { id: command.id, controller, pending: [] };
|
|
348
394
|
queryHistory.push(command.prompt);
|
|
349
395
|
// 首个模型请求前也要有可恢复的用户轮。run-coordinator 的 cancellation checkpoint
|
|
350
396
|
// 是内存快照、不会调用 onCheckpoint;这里追加 user 后再落盘,避免首轮崩溃只剩侧栏标题。
|
|
351
|
-
const userInput = command
|
|
352
|
-
? [
|
|
353
|
-
...(command.prompt ? [{ type: 'text', text: command.prompt }] : []),
|
|
354
|
-
...command.attachments.flatMap((attachment) => {
|
|
355
|
-
if (attachment.dataUrl)
|
|
356
|
-
return [{ type: 'image_url', name: attachment.name, image_url: { url: attachment.dataUrl } }];
|
|
357
|
-
if (typeof attachment.text !== 'string')
|
|
358
|
-
return [];
|
|
359
|
-
// name/attachment/truncated 是会话回放元数据,transport 发送前统一移除。
|
|
360
|
-
return [
|
|
361
|
-
{
|
|
362
|
-
type: 'text',
|
|
363
|
-
name: attachment.name,
|
|
364
|
-
attachment: true,
|
|
365
|
-
truncated: attachment.truncated === true,
|
|
366
|
-
text: `用户附件 ${JSON.stringify(attachment.name)} 的提取文本如下。${attachment.truncated ? '(内容已截断,仅提供前 100000 字符)' : ''}\n\n${attachment.text}`,
|
|
367
|
-
},
|
|
368
|
-
];
|
|
369
|
-
}),
|
|
370
|
-
]
|
|
371
|
-
: command.prompt;
|
|
397
|
+
const userInput = inputForRun(command);
|
|
372
398
|
history.push({ role: 'user', content: userInput });
|
|
373
399
|
persistSession();
|
|
374
400
|
emit('run_started', {
|
|
@@ -413,6 +439,11 @@ async function run(command) {
|
|
|
413
439
|
planMode,
|
|
414
440
|
};
|
|
415
441
|
emit('tool_route', initialToolRoute, command.id);
|
|
442
|
+
const memoryEnabled = isMemoryEnabled();
|
|
443
|
+
const memoryTail = buildMemoryTailSnapshot(memoryEnabled);
|
|
444
|
+
const memoryRecall = memoryEnabled && isTurnRecallEnabled()
|
|
445
|
+
? buildTurnRecallSection(command.prompt, { excludeIds: memoryTail.shownIds })
|
|
446
|
+
: '';
|
|
416
447
|
const result = await runtime().run({
|
|
417
448
|
turn: 'new',
|
|
418
449
|
turnLabel: command.prompt.split('\n')[0]?.slice(0, 40) ?? command.prompt.slice(0, 40),
|
|
@@ -420,6 +451,7 @@ async function run(command) {
|
|
|
420
451
|
userInput,
|
|
421
452
|
// 上面已把用户轮写入首个持久化检查点,core 不能再 append 一次。
|
|
422
453
|
continueFromHistory: true,
|
|
454
|
+
drainUserMessages: () => activeRun?.pending.splice(0) ?? [],
|
|
423
455
|
signal: controller.signal,
|
|
424
456
|
hooks: hooksFor(command.id),
|
|
425
457
|
contextState,
|
|
@@ -428,11 +460,8 @@ async function run(command) {
|
|
|
428
460
|
traceContext: { sessionId },
|
|
429
461
|
onTraceEvent: appendCurrentSessionTraceEvent,
|
|
430
462
|
permissionPrompt: (request) => waitForApproval(command.id, request),
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
// 排除 memoryTailChangedIds() 是刻意的——那批条目已由尾注播报,同一轮不重复讲。
|
|
434
|
-
memoryTail: buildMemoryTailSection(isMemoryEnabled()),
|
|
435
|
-
memoryRecall: turnRecallFor(command.prompt),
|
|
463
|
+
memoryTail: memoryTail.text,
|
|
464
|
+
memoryRecall,
|
|
436
465
|
});
|
|
437
466
|
lastToolGroups = toolPolicy.groupNames;
|
|
438
467
|
persistSession();
|
|
@@ -475,6 +504,13 @@ async function run(command) {
|
|
|
475
504
|
approvals.delete(approvalId);
|
|
476
505
|
}
|
|
477
506
|
}
|
|
507
|
+
// Accepted messages must survive cancellation or a step-limit exit before consumption.
|
|
508
|
+
const remaining = activeRun?.pending.splice(0) ?? [];
|
|
509
|
+
if (remaining.length > 0) {
|
|
510
|
+
for (const content of remaining)
|
|
511
|
+
history.push({ role: 'user', content });
|
|
512
|
+
persistSession();
|
|
513
|
+
}
|
|
478
514
|
activeRun = null;
|
|
479
515
|
}
|
|
480
516
|
}
|
|
@@ -507,6 +543,7 @@ async function compact(command) {
|
|
|
507
543
|
if (!sessionId)
|
|
508
544
|
createSession();
|
|
509
545
|
emit('status', { value: 'compacting' }, command.id);
|
|
546
|
+
emit('context_compacting', { manual: true, ...(command.focus ? { focus: command.focus } : {}) }, command.id);
|
|
510
547
|
const activeRuntime = runtime();
|
|
511
548
|
const log = await activeRuntime.compact(history, {
|
|
512
549
|
focus: command.focus,
|
|
@@ -518,6 +555,19 @@ async function compact(command) {
|
|
|
518
555
|
// 旧实测锚点属于压缩前请求,不能跨摘要边界继续外推。
|
|
519
556
|
contextState.promptAnchor = undefined;
|
|
520
557
|
const usage = contextUsageSnapshot();
|
|
558
|
+
// 与自动路径同一个事件形状:GUI 的会话流据此留一条「已压缩」系统行(切走再回来还在)。
|
|
559
|
+
// compact_done 保留给旧客户端的 toast,两条事件在这里是有意的分工,不是重复。
|
|
560
|
+
emit('context_compacted', {
|
|
561
|
+
manual: true,
|
|
562
|
+
summarized: log.compactDetail?.reason === 'summarize',
|
|
563
|
+
reason: log.compactDetail?.reason,
|
|
564
|
+
historyRebuilt: log.historyMutation === 'rebuild',
|
|
565
|
+
beforeTokens: log.compactDetail?.estimateBefore,
|
|
566
|
+
afterTokens: log.compactDetail?.estimateAfter,
|
|
567
|
+
usagePercent: usage.percent,
|
|
568
|
+
contextUsage: usage,
|
|
569
|
+
contextWindow: runtime().context.config.contextWindowTokens,
|
|
570
|
+
}, command.id);
|
|
521
571
|
emit('compact_done', {
|
|
522
572
|
compacted: log.compactHistoryCalled,
|
|
523
573
|
beforeTokens: log.compactDetail?.estimateBefore,
|
|
@@ -1346,6 +1396,10 @@ function requestShutdownCancellation() {
|
|
|
1346
1396
|
}
|
|
1347
1397
|
}
|
|
1348
1398
|
const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
1399
|
+
// host 的 stdout 是 NDJSON 协议通道:layout.contentWrite / Spinner 的「非 TTY 直接写」兜底
|
|
1400
|
+
// 会把压缩行、图片卡片行这类裸文本灌进来,客户端 JSON.parse 失败后当 diagnostic 丢掉。
|
|
1401
|
+
// 用户可见反馈必须走下面的事件(context_compacted / image_relief …),兜底写一律静音。
|
|
1402
|
+
muteStdoutOutput();
|
|
1349
1403
|
const pendingCommands = new Set();
|
|
1350
1404
|
const heartbeatTimer = startHeartbeat();
|
|
1351
1405
|
const startupPromise = initializeRuntime();
|