mocode-ai 1.9.5 → 1.9.8

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.
Files changed (45) hide show
  1. package/dist/agent/index.js +27 -0
  2. package/dist/agent/model-turn.js +6 -6
  3. package/dist/agent/request-governor.js +1 -1
  4. package/dist/context/vision-window.js +24 -9
  5. package/dist/host/protocol.js +4 -1
  6. package/dist/host/stdio.js +45 -1
  7. package/dist/index.js +7 -0
  8. package/dist/jobs/dir-snapshot.js +332 -0
  9. package/dist/jobs/worktree.js +78 -20
  10. package/dist/llm/index.js +3 -0
  11. package/dist/orchestrator/board.js +332 -0
  12. package/dist/orchestrator/cli.js +628 -0
  13. package/dist/orchestrator/index.js +4 -0
  14. package/dist/orchestrator/integrate.js +344 -0
  15. package/dist/orchestrator/lane-channel.js +146 -0
  16. package/dist/orchestrator/lane-executor.js +439 -0
  17. package/dist/orchestrator/lane-repl.js +154 -0
  18. package/dist/orchestrator/lane-site.js +255 -0
  19. package/dist/orchestrator/lanes.js +72 -0
  20. package/dist/orchestrator/lease.js +132 -0
  21. package/dist/orchestrator/live-log.js +193 -0
  22. package/dist/orchestrator/repl.js +435 -0
  23. package/dist/orchestrator/review.js +135 -0
  24. package/dist/orchestrator/scheduler.js +673 -0
  25. package/dist/orchestrator/scope.js +88 -0
  26. package/dist/orchestrator/state.js +533 -0
  27. package/dist/orchestrator/store.js +221 -0
  28. package/dist/orchestrator/supervisor-prompt.js +54 -0
  29. package/dist/orchestrator/supervisor.js +798 -0
  30. package/dist/orchestrator/tail.js +508 -0
  31. package/dist/orchestrator/task-prompt.js +93 -0
  32. package/dist/orchestrator/terminal.js +269 -0
  33. package/dist/orchestrator/tools.js +392 -0
  34. package/dist/orchestrator/types.js +1 -0
  35. package/dist/orchestrator/watch-panel.js +154 -0
  36. package/dist/orchestrator/worker.js +475 -0
  37. package/dist/orchestrator/workspaces.js +191 -0
  38. package/dist/repl/commands/memory.js +1 -1
  39. package/dist/repl/runtime.js +16 -2
  40. package/dist/session/store.js +1 -1
  41. package/dist/tools/builtins/ask-human.js +27 -6
  42. package/dist/ui/handoff-block.js +91 -0
  43. package/dist/ui/layout-internal/statusbar.js +2 -1
  44. package/dist/ui/prompt-internal/editor.js +49 -0
  45. package/package.json +2 -2
@@ -0,0 +1,191 @@
1
+ // 整机工作区清单:Super Agent 需要知道「这台机器上哪里跑过 mocode」才能派活。
2
+ //
3
+ // 两个来源:
4
+ // 1. 全局注册表 `~/.mocode/workspaces.jsonl`(每次启动/`/cd` 自动登记,见 src/workspace/registry.ts);
5
+ // 2. 显式 `--scan-roots`:在这些根下做有限深度扫描,找带 `.mocode/sessions` 的目录。
6
+ //
7
+ // 刻意不扫全盘:深度上限、跳过 node_modules / .git / dist 等,避免变成一次磁盘遍历。
8
+ // 目录消失了不删记录,只标 `exists: false`——派活前必须校验存在性。
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { gitRepositoryDirty, gitTopLevel } from '../jobs/worktree.js';
13
+ import { readWorkspaceRegistry } from '../workspace/registry.js';
14
+ import { listOrchestrations } from './store.js';
15
+ /** 扫描时整目录跳过的名字(不区分层级)。 */
16
+ const SCAN_SKIP = new Set([
17
+ 'node_modules',
18
+ '.git',
19
+ 'dist',
20
+ 'dist-tests',
21
+ 'build',
22
+ 'out',
23
+ 'target',
24
+ '.next',
25
+ '.cache',
26
+ 'coverage',
27
+ '__pycache__',
28
+ '.venv',
29
+ 'venv',
30
+ ]);
31
+ const MAX_SCAN_DEPTH = 3;
32
+ function sessionList(root) {
33
+ const dir = path.join(root, '.mocode', 'sessions');
34
+ let names;
35
+ try {
36
+ names = fs
37
+ .readdirSync(dir, { withFileTypes: true })
38
+ .filter((entry) => entry.isDirectory() && /^\d{8}-\d{6}/.test(entry.name))
39
+ .map((entry) => entry.name);
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ return names
45
+ .sort()
46
+ .reverse()
47
+ .slice(0, 12)
48
+ .map((id) => {
49
+ try {
50
+ const record = JSON.parse(fs.readFileSync(path.join(dir, id, 'session.json'), 'utf8'));
51
+ const first = record.history?.find((message) => message.role === 'user');
52
+ return {
53
+ id,
54
+ createdAt: record.createdAt,
55
+ firstUser: typeof first?.content === 'string' ? first.content.slice(0, 80) : undefined,
56
+ };
57
+ }
58
+ catch {
59
+ return { id };
60
+ }
61
+ });
62
+ }
63
+ function laneRefs(root) {
64
+ let runs;
65
+ try {
66
+ runs = listOrchestrations(root);
67
+ }
68
+ catch {
69
+ return [];
70
+ }
71
+ const refs = [];
72
+ for (const run of runs) {
73
+ if (run.status === 'completed' || run.status === 'cancelled')
74
+ continue;
75
+ for (const lane of Object.values(run.lanes ?? {})) {
76
+ if (path.resolve(lane.workspaceRoot) !== path.resolve(root))
77
+ continue;
78
+ refs.push({
79
+ runId: run.id,
80
+ laneId: lane.id,
81
+ mode: lane.mode ?? 'worktree',
82
+ status: lane.closed ? 'closed' : 'open',
83
+ sessionId: lane.sessionId,
84
+ });
85
+ }
86
+ }
87
+ return refs;
88
+ }
89
+ function describeWorkspace(root, source, options) {
90
+ const absolute = path.resolve(root);
91
+ const exists = fs.existsSync(absolute);
92
+ const top = exists ? gitTopLevel(absolute) : null;
93
+ const info = {
94
+ root: absolute,
95
+ name: path.basename(absolute) || absolute,
96
+ source,
97
+ exists,
98
+ git: Boolean(top && path.resolve(top) === absolute),
99
+ sessions: options.includeSessions === false ? [] : sessionList(absolute),
100
+ lanes: options.includeLanes === false ? [] : laneRefs(absolute),
101
+ };
102
+ if (info.git) {
103
+ info.dirty = gitRepositoryDirty(absolute);
104
+ try {
105
+ const head = fs.readFileSync(path.join(absolute, '.git', 'HEAD'), 'utf8').trim();
106
+ info.branch = head.startsWith('ref: refs/heads/') ? head.slice('ref: refs/heads/'.length) : head.slice(0, 8);
107
+ }
108
+ catch {
109
+ // worktree 的 .git 是文件,读不到分支就留空。
110
+ }
111
+ }
112
+ return info;
113
+ }
114
+ /** 有限深度扫描:只认带 `.mocode/sessions` 的目录。 */
115
+ function scanForWorkspaces(root, maxDepth) {
116
+ const found = [];
117
+ const walk = (dir, depth) => {
118
+ if (depth > maxDepth)
119
+ return;
120
+ if (fs.existsSync(path.join(dir, '.mocode', 'sessions')))
121
+ found.push(path.resolve(dir));
122
+ let entries;
123
+ try {
124
+ entries = fs.readdirSync(dir, { withFileTypes: true });
125
+ }
126
+ catch {
127
+ return;
128
+ }
129
+ for (const entry of entries) {
130
+ if (!entry.isDirectory())
131
+ continue;
132
+ if (SCAN_SKIP.has(entry.name))
133
+ continue;
134
+ walk(path.join(dir, entry.name), depth + 1);
135
+ }
136
+ };
137
+ walk(path.resolve(root), 0);
138
+ return found;
139
+ }
140
+ export function listWorkspaces(options = {}) {
141
+ // 去重键用小写(Windows 大小写不敏感),但保留首次登记时的原始大小写用于展示与派活。
142
+ const byRoot = new Map();
143
+ const add = (root, source) => {
144
+ const absolute = path.resolve(root);
145
+ const key = absolute.toLowerCase();
146
+ if (!byRoot.has(key))
147
+ byRoot.set(key, { root: absolute, source });
148
+ };
149
+ for (const entry of readWorkspaceRegistry())
150
+ add(entry.root, 'registry');
151
+ for (const root of options.scanRoots ?? []) {
152
+ for (const found of scanForWorkspaces(root, options.maxDepth ?? MAX_SCAN_DEPTH))
153
+ add(found, 'scan');
154
+ }
155
+ for (const root of options.roots ?? []) {
156
+ if (fs.existsSync(root))
157
+ add(root, 'arg');
158
+ }
159
+ return [...byRoot.values()]
160
+ .map(({ root, source }) => describeWorkspace(root, source, options))
161
+ .sort((a, b) => Number(b.exists) - Number(a.exists) || a.root.localeCompare(b.root));
162
+ }
163
+ export function formatWorkspaces(list) {
164
+ if (list.length === 0)
165
+ return 'No known workspaces. Run mocode inside a project, or pass --scan-roots <dir>.\n';
166
+ const lines = [];
167
+ for (const item of list) {
168
+ const flags = [
169
+ item.exists ? '' : 'missing',
170
+ item.git ? `git:${item.branch ?? '?'}${item.dirty ? '*' : ''}` : 'no-git',
171
+ ].filter(Boolean);
172
+ lines.push(`${item.root} [${flags.join(' ')}]`);
173
+ const detail = [];
174
+ if (item.sessions.length > 0) {
175
+ const latest = item.sessions[0];
176
+ const preview = latest.firstUser ? ` "${latest.firstUser}"` : '';
177
+ detail.push(`${item.sessions.length} recent session(s), latest ${latest.id}${preview}`);
178
+ }
179
+ else {
180
+ detail.push('no sessions');
181
+ }
182
+ for (const lane of item.lanes)
183
+ detail.push(`lane ${lane.laneId} (${lane.mode}, ${lane.status}) run ${lane.runId}`);
184
+ lines.push(` ${detail.join(' · ')}`);
185
+ }
186
+ return `${lines.join('\n')}\n`;
187
+ }
188
+ export function defaultScanRoots() {
189
+ // 只给「用户主目录下一层」这种合理默认,不递归全盘。
190
+ return [os.homedir()];
191
+ }
@@ -4,7 +4,7 @@
4
4
  * 只读概览 + 后台反思触发 + 长期画像检视/纠错 + **用户主权面**(R8:导出/导入/批量遗忘/暂停)。
5
5
  * /memory_switch /memory_status 是**配置写入**命令,与 /subagent /fe /mcp 同属 tool-group,
6
6
  * 放 tool-group.ts,不在这里。
7
- * 注意:顶层 /profile 被刻意禁用(见 tests/tool-profiles.test.ts),画像命令并入 /memory 组。
7
+ * 注意:顶层 /profile 被刻意禁用(见 tests/tools/tool-profiles.test.ts),画像命令并入 /memory 组。
8
8
  */
9
9
  import * as layout from '../../ui/layout.js';
10
10
  import { ui } from '../../ui/theme.js';
@@ -218,14 +218,13 @@ function awaitPendingRecall(input) {
218
218
  pendingTimer.unref?.();
219
219
  });
220
220
  }
221
- // ── textOf / queryHistoryFromMessages / renderHistory 已移到 ./message-format.ts ──
222
221
  /**
223
222
  * 交互式 REPL:全屏 TUI(alt screen + 固定底栏)。INPUT 态底栏=状态行+输入框(raw mode 等按键);
224
223
  * 提交后 enterRunningMode(底栏改 dim 占位、光标回内容续写位),命令分发与 runAgent 的流式输出经
225
224
  * contentWrite 落入内容区(滚动区域内自动滚动,底栏不动)。history 由本模块持有,在轮次间持久;
226
225
  * agent 只读取并追加(+ 经 session/ 压缩)。每轮成功结束后自动落盘,退出后可用 --resume / /resume 续接。
227
226
  */
228
- export async function startRepl(initialHistory, sessionId, sandboxRootOverride, initialQueryHistory, initialLastToolGroups) {
227
+ export async function startRepl(initialHistory, sessionId, sandboxRootOverride, initialQueryHistory, initialLastToolGroups, hooks = {}) {
229
228
  // 模式重置:agentMode 不落盘,每个 REPL 会话从 auto 开始(/resume / --resume 亦重置)。
230
229
  setAgentMode('auto');
231
230
  // 钉死本会话模型:之后运行中 agent 一律用此值,其它窗口的 /model switch 不会影响本窗口。
@@ -411,6 +410,10 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
411
410
  if (!history.some((m) => m.role === 'user')) {
412
411
  layout.writeWelcomeBlock(welcomeLines());
413
412
  }
413
+ // 外部观察者(supervise 派活的 lane):画面已就绪、会话 id 已确定,可以接活了。
414
+ // 放在首帧渲染之后而不是函数入口:否则 supervisor 会以为「已经能派」,
415
+ // 派来的话却要等人把那圈启动流程跑完才被消费,中间的空窗看起来像卡死。
416
+ hooks.onReady?.({ sessionId: currentSessionId, workspacePath: sandboxRootOverride ?? process.cwd() });
414
417
  // R9.4 空库提示:记忆开着但一条 active 都没有 → 说清「怎么让它有」,而不是让用户
415
418
  // 对着空库空转。只在启动时提示一次(不是每轮),且不给 UI 常驻噪音:
416
419
  // 「零感知」路线要求的是**行为**里有记忆,不是界面上反复提醒记忆的存在。
@@ -566,6 +569,8 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
566
569
  let signal;
567
570
  let toolPolicy = inheritedToolPolicy;
568
571
  let initialToolRoute;
572
+ /** 本轮最后一条 assistant 正文(外部观察者要在轮末拿它当交接摘要)。 */
573
+ let finalText = null;
569
574
  // 继承 toolPolicy 的合成执行轮没有独立路由;真实用户轮在 await routeToolGroups 完成后置 true。
570
575
  // 路由完成前 Ctrl+C = 撤回本轮消息(routedCancel),之后才是"中断 agent 执行"(原 abort 语义)。
571
576
  let routingDone = toolPolicy != null;
@@ -667,6 +672,7 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
667
672
  if (result.terminationReason === 'max_steps' && result.finalText) {
668
673
  layout.contentWrite(result.finalText.endsWith('\n') ? result.finalText : `${result.finalText}\n`);
669
674
  }
675
+ finalText = result.finalText;
670
676
  if (toolPolicy)
671
677
  lastToolGroups = toolPolicy.groupNames;
672
678
  // 本轮 token 累计(底栏模式 chip 右边显示)。undefined = 后端不开 include_usage。
@@ -767,6 +773,10 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
767
773
  }
768
774
  if (!routedCancel)
769
775
  layout.contentWrite('\n'); // 轮次之间空行(路由撤回由主循环 rewindContent 擦除,不补空行)
776
+ // 外部观察者(supervise 派活的 lane):这一轮跑完了,交出结论。
777
+ // 撤回的轮次不算一轮——它什么都没执行,报上去会让控制面误判任务已完成。
778
+ if (!routedCancel)
779
+ hooks.onTurnFinished?.({ ok, finalText });
770
780
  return { ok, toolPolicy, routedCancel };
771
781
  };
772
782
  /** 把 picker 选中的会话加载进 REPL(刷 history + 重建 snapshots + 重画)。/resume / /sessions 共用。 */
@@ -857,6 +867,10 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
857
867
  pendingAttachments = [];
858
868
  syncPendingAttachChips();
859
869
  },
870
+ // 第二输入源(supervise 派活 / 插话):只在空闲输入框里取,人正在打字时不抢。
871
+ // 不传就是零行为变化——手敲 mocode 永远走不到这支分支。
872
+ ...(hooks.takeExternalTurn ? { takeExternalTurn: hooks.takeExternalTurn } : {}),
873
+ ...(hooks.externalExitRequested ? { externalExitRequested: hooks.externalExitRequested } : {}),
860
874
  // Ctrl+R / Ctrl+P 历史搜索候选源:惰性工厂——当前会话内存 queryHistory + 最近落盘会话,
861
875
  // 聚合要读盘,只有面板真正打开(Ctrl+R/P)才求值,平常轮次零开销
862
876
  history: () => collectQueryHistory(queryHistory).map((e) => e.text),
@@ -86,7 +86,7 @@ export class SessionStore {
86
86
  * 缓存的是「已 mkdir 成功」这件事,不是路径存在性。**代价**:外部删掉目录后缓存会失真。
87
87
  * 兜底是三个写盘方法统一的「失败 → invalidateEnsuredDir → 重试一次」模式
88
88
  * (见 appendTrace / appendUsage / save),既保住性能又不丢数据。
89
- * 护栏见 tests/session-dir-cache.test.ts 的「外部删除后自愈」三例。
89
+ * 护栏见 tests/session/session-dir-cache.test.ts 的「外部删除后自愈」三例。
90
90
  */
91
91
  ensuredDirs = new Set();
92
92
  constructor(options = {}) {
@@ -1,6 +1,18 @@
1
1
  import { promptWithMail } from '../../mail/index.js';
2
2
  import { sendState } from '../../pet/bridge.js';
3
3
  import { t } from '../../i18n/index.js';
4
+ /**
5
+ * 进程级问答通道。缺省 null = 直接弹本地面板。
6
+ * Supervised Host 在启动时注入一条「转成 approval_requested 事件」的通道,
7
+ * 这样 Worker 里的 ask_human 就不是「不可用」,而是由控制面转给真人。
8
+ */
9
+ let askHumanHandler = null;
10
+ export function setAskHumanHandler(handler) {
11
+ askHumanHandler = handler;
12
+ }
13
+ export function getAskHumanHandler() {
14
+ return askHumanHandler;
15
+ }
4
16
  /** 把单个选项元素安全地转成 {label, detail}。LLM 有时传对象而不是字符串,这里提取可读字段。 */
5
17
  function optionToChoice(o) {
6
18
  if (o === null || o === undefined)
@@ -158,13 +170,22 @@ export const askHumanTool = {
158
170
  const question = String(args.question ?? '');
159
171
  const options = coerceOptions(args.options);
160
172
  const context = args.context ? String(args.context) : undefined;
173
+ // 宿主注入了通道(Supervised Host)→ 把问题交上去由控制面转给真人。
174
+ // 没有通道又有 MOCODE_SUPERVISED_WORKER=1:说明这次派活没有能应答的人(单发 CLI),
175
+ // 非 TTY 面板会自动选首项,等于替用户做关键决定——所以明确报不可用,让 Worker 写进 handoff risks。
176
+ const handler = askHumanHandler;
177
+ if (!handler && process.env.MOCODE_SUPERVISED_WORKER === '1') {
178
+ return 'ask_human is unavailable in this supervised worker: no human can answer here. Do not guess a decision; record the open question and its options in your handoff risks and stop.';
179
+ }
161
180
  sendState('waiting_human');
162
- const result = await promptWithMail({
163
- type: options.length > 0 ? 'choice' : 'input',
164
- title: question,
165
- options: options.length > 0 ? options : undefined,
166
- detail: context,
167
- });
181
+ const result = handler
182
+ ? await handler({ question, options, ...(context ? { context } : {}) })
183
+ : await promptWithMail({
184
+ type: options.length > 0 ? 'choice' : 'input',
185
+ title: question,
186
+ options: options.length > 0 ? options : undefined,
187
+ detail: context,
188
+ });
168
189
  if (result.action === 'cancelled') {
169
190
  return t('askHuman.cancelled');
170
191
  }
@@ -0,0 +1,91 @@
1
+ // 把 `<mocode_handoff>…</mocode_handoff>` 从**显示**路径上摘掉。
2
+ //
3
+ // 为什么需要:supervise 派活时,任务提示词要求 worker 以一个机器可读的交接块收尾
4
+ // (见 `orchestrator/task-prompt.ts`),控制面靠它解析 summary / validation / risks。
5
+ // 但 lane 窗口里跑的是**一个真的 mocode REPL**,模型的最后一条正文原样流式写屏,
6
+ // 于是那一大坨 JSON 就摊在用户眼前——它对人没有信息量,还把结论挤没了。
7
+ //
8
+ // 三条约束:
9
+ // 1. **只影响显示**。`finalText` 必须完整保留,否则 `parseHandoff` 拿不到块,任务判不出结论。
10
+ // 2. **必须跨 chunk**。流式是一小块一小块来的,标签本身会被切开(`<mocode_han` + `doff>`),
11
+ // 所以不能对每个 chunk 单独做正则替换。
12
+ // 3. **未闭合也要收场**。模型可能被中断、或忘了写闭合标签;flush() 时把残留吞掉,
13
+ // 不能因为「没等到闭合」就把半截 JSON 吐到屏幕上。
14
+ const OPEN = '<mocode_handoff>';
15
+ const CLOSE = '</mocode_handoff>';
16
+ /** 从 `text` 尾部找出「可能是 OPEN / CLOSE 前缀」的最长后缀长度,用于跨 chunk 保持。 */
17
+ function trailingPartial(text, tag) {
18
+ const max = Math.min(tag.length - 1, text.length);
19
+ for (let size = max; size > 0; size--) {
20
+ if (text.endsWith(tag.slice(0, size)))
21
+ return size;
22
+ }
23
+ return 0;
24
+ }
25
+ export function createHandoffStripper() {
26
+ /** 已收到、但还没决定能不能显示的尾巴。 */
27
+ let pending = '';
28
+ /** true = 正处在一个 handoff 块内部(内容一律丢弃,直到遇到 CLOSE)。 */
29
+ let inside = false;
30
+ return {
31
+ push(chunk) {
32
+ pending += chunk;
33
+ let out = '';
34
+ for (;;) {
35
+ if (inside) {
36
+ const end = pending.indexOf(CLOSE);
37
+ if (end < 0) {
38
+ // 还没闭合:只保留可能是 CLOSE 前缀的尾巴,其余全部丢弃。
39
+ const keep = trailingPartial(pending, CLOSE);
40
+ pending = keep > 0 ? pending.slice(-keep) : '';
41
+ return out;
42
+ }
43
+ pending = pending.slice(end + CLOSE.length);
44
+ inside = false;
45
+ // 块后面紧跟的空行/换行一并吃掉,避免正文区留一片空白。
46
+ pending = pending.replace(/^[ \t]*\r?\n/, '');
47
+ continue;
48
+ }
49
+ const start = pending.indexOf(OPEN);
50
+ if (start >= 0) {
51
+ out += pending.slice(0, start);
52
+ pending = pending.slice(start + OPEN.length);
53
+ inside = true;
54
+ continue;
55
+ }
56
+ // 没有完整标签:保留可能是 OPEN 前缀的尾巴,其余可以安全显示。
57
+ const keep = trailingPartial(pending, OPEN);
58
+ out += keep > 0 ? pending.slice(0, pending.length - keep) : pending;
59
+ pending = keep > 0 ? pending.slice(-keep) : '';
60
+ return out;
61
+ }
62
+ },
63
+ flush() {
64
+ // 块内未闭合:整段丢弃(那是协议残渣,不是给人看的内容)。
65
+ if (inside) {
66
+ pending = '';
67
+ inside = false;
68
+ return '';
69
+ }
70
+ // 块外但只剩一个标签前缀(`<mocode_han`):这一轮永远等不到它的后半截了,
71
+ // 吐出去只会让人看见半截标签,同样丢弃。
72
+ const rest = trailingPartial(pending, OPEN) === pending.length ? '' : pending;
73
+ pending = '';
74
+ return rest;
75
+ },
76
+ };
77
+ }
78
+ /**
79
+ * 进程级开关:只有「派出去的那个 mocode 窗口」需要摘块。
80
+ *
81
+ * 用进程级而不是每轮参数,是因为过滤发生在 `agent/index.ts` 的 TUI hooks 里,那条路径
82
+ * 拿不到调用方上下文;而 lane 窗口本身是独立进程,一个开关就够且不会串味。
83
+ * 手动敲 `mocode` 的窗口永远不打开它(默认 false)。
84
+ */
85
+ let suppressed = false;
86
+ export function setHandoffDisplaySuppressed(value) {
87
+ suppressed = value;
88
+ }
89
+ export function handoffDisplaySuppressed() {
90
+ return suppressed;
91
+ }
@@ -92,7 +92,8 @@ export function composeModelLine(status, cols) {
92
92
  const modePart = modeTag ? `${modeColor}${modeTag}${ui.reset}` : '';
93
93
  const modeW = modeTag ? displayWidth(modeTag) : 0;
94
94
  // 切换提示:告诉用户怎么切模式。灰(dim)降优先级,不与 modeTag 抢色;只在有 modeTag 时出现。
95
- const HINT = t('status.modeSwitch');
95
+ // modeHint 可覆盖(空串=不显示):没有模式切换的入口(supervisor)不该提示一个按了没反应的键。
96
+ const HINT = status.modeHint ?? t('status.modeSwitch');
96
97
  const hintW = modeTag ? displayWidth(HINT) : 0;
97
98
  const hintPart = modeTag ? `${ui.dim}${HINT}${ui.reset}` : '';
98
99
  // P3 effort chip:非 auto 时显示,与 modeTag 同级色(运行时状态),优先级在 hint 之上。
@@ -59,6 +59,8 @@ export async function promptWithSlashMenu(opts) {
59
59
  let resolved = false;
60
60
  let resolve;
61
61
  let reject;
62
+ /** 第二输入源(supervise 派活)的轮询定时器;只有传了 takeExternalTurn 才存在。 */
63
+ let externalTimer = null;
62
64
  /** 菜单行(预渲染,带色)——向上展开进内容区底,由 layout 贴入。最多显示 MENU_MAX_VISIBLE 条,支持上下滚动。 */
63
65
  function menuLines() {
64
66
  if (!menuOpen || filtered.length === 0)
@@ -375,9 +377,51 @@ export async function promptWithSlashMenu(opts) {
375
377
  computeFiltered();
376
378
  redraw();
377
379
  }
380
+ /**
381
+ * 第二输入源轮询:输入框为空时问一次「有没有别处派来的话」(supervise 派活 / 插话)。
382
+ *
383
+ * 三条克制:
384
+ * 1. 只有空输入框才取——人正在打字时绝不抢字,否则打一半被顶掉是最难受的体验;
385
+ * 2. 取到就直接提交(等同用户按 Enter),不是预填——派活的人不在这个终端前,没人按 Enter;
386
+ * 3. 轮询自身不画屏,只有真的要提交时才走 submit 路径,空闲时零可见开销。
387
+ */
388
+ function pollExternalTurn() {
389
+ if (resolved)
390
+ return;
391
+ // 关窗请求优先于派活:已经收工了就不该再开新回合。
392
+ // 走 finish(null) 而不是自己复原终端:与 Ctrl+D 同一条退出路径,REPL 才会跑到
393
+ // exitAltScreen(alt screen / raw / 鼠标追踪 / margins 一处都不漏)。
394
+ if (opts.externalExitRequested?.()) {
395
+ finish(null);
396
+ return;
397
+ }
398
+ if (!opts.takeExternalTurn)
399
+ return;
400
+ const isEmpty = segs.length === 1 && !segs[0].frozen && segs[0].text === '';
401
+ if (!isEmpty || pasteState.pasting)
402
+ return;
403
+ let external = null;
404
+ try {
405
+ external = opts.takeExternalTurn();
406
+ }
407
+ catch {
408
+ return; // 通道读失败不该打断输入
409
+ }
410
+ if (!external || external.trim() === '')
411
+ return;
412
+ segs = [{ frozen: false, text: external }];
413
+ curSeg = 0;
414
+ curOff = segs[0].text.length;
415
+ computeFiltered();
416
+ submit();
417
+ }
378
418
  function cleanup() {
379
419
  layout.setPasteHandler(null);
380
420
  layout.setCursorChangeHandler(null);
421
+ if (externalTimer) {
422
+ clearInterval(externalTimer);
423
+ externalTimer = null;
424
+ }
381
425
  try {
382
426
  stdin.setRawMode(false);
383
427
  }
@@ -975,6 +1019,11 @@ export async function promptWithSlashMenu(opts) {
975
1019
  layout.setCursorChangeHandler(applyExternalCursor); // 鼠标左键单击输入框(未拖动)→ 改 cl/cc 到点击位;cleanup 时注销
976
1020
  stdin.resume();
977
1021
  emitter.on('keypress', onKey);
1022
+ // 第二输入源(supervise 派活 / 关窗请求):只有传了任一回调才起定时器,其它调用点零开销。
1023
+ if (opts.takeExternalTurn || opts.externalExitRequested) {
1024
+ externalTimer = setInterval(pollExternalTurn, 400);
1025
+ externalTimer.unref?.();
1026
+ }
978
1027
  computeFiltered();
979
1028
  redraw();
980
1029
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mocode-ai",
3
- "version": "1.9.5",
3
+ "version": "1.9.8",
4
4
  "description": "终端编码 agent:LLM + tool-call 循环 + 流式输出(含思考)+ 27 个工具,接任意 OpenAI 兼容后端。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "start": "tsx src/index.ts",
25
25
  "build": "npm run build --workspace @mocode/protocol && npm run build --workspace @mocode/runtime && tsc -p tsconfig.build.json",
26
26
  "build:electron": "npm run build && npm run check:electron-boundary && npm run typecheck --workspace mocode-work && npm run build --workspace mocode-work && npm run typecheck --workspace mocode-pet-app && npm run build --workspace mocode-pet-app && npm run smoke:runtime-host",
27
- "test": "tsc -p tsconfig.test-build.json && node --test --experimental-test-isolation=none \"dist-tests/tests/*.test.js\"",
27
+ "test": "tsc -p tsconfig.test-build.json && node --test --experimental-test-isolation=none \"dist-tests/tests/**/*.test.js\"",
28
28
  "typecheck": "npm run typecheck --workspace @mocode/protocol && npm run typecheck --workspace @mocode/runtime && tsc --noEmit && tsc -p tests/tsconfig.json && tsc -p evals/tsconfig.json",
29
29
  "check:electron-boundary": "npm run check:electron-boundary --workspace @mocode/runtime",
30
30
  "smoke:runtime-host": "npm run smoke:host --workspace @mocode/runtime",