coremind-cli 1.0.1 → 1.4.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.
Files changed (42) hide show
  1. package/README.md +6 -2
  2. package/dist/approval.d.ts.map +1 -1
  3. package/dist/approval.js +19 -38
  4. package/dist/approval.js.map +1 -1
  5. package/dist/commands/chat.d.ts +10 -1
  6. package/dist/commands/chat.d.ts.map +1 -1
  7. package/dist/commands/chat.js +307 -70
  8. package/dist/commands/chat.js.map +1 -1
  9. package/dist/commands/doctor.d.ts +1 -0
  10. package/dist/commands/doctor.d.ts.map +1 -1
  11. package/dist/commands/doctor.js +42 -15
  12. package/dist/commands/doctor.js.map +1 -1
  13. package/dist/commands/eval.d.ts.map +1 -1
  14. package/dist/commands/eval.js +26 -5
  15. package/dist/commands/eval.js.map +1 -1
  16. package/dist/commands/run.d.ts.map +1 -1
  17. package/dist/commands/run.js +104 -25
  18. package/dist/commands/run.js.map +1 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +3 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/project-code-trust.d.ts +5 -0
  23. package/dist/project-code-trust.d.ts.map +1 -0
  24. package/dist/project-code-trust.js +64 -0
  25. package/dist/project-code-trust.js.map +1 -0
  26. package/dist/render.d.ts +29 -1
  27. package/dist/render.d.ts.map +1 -1
  28. package/dist/render.js +197 -12
  29. package/dist/render.js.map +1 -1
  30. package/dist/terminal-input.d.ts +67 -0
  31. package/dist/terminal-input.d.ts.map +1 -0
  32. package/dist/terminal-input.js +208 -0
  33. package/dist/terminal-input.js.map +1 -0
  34. package/dist/terminal-view.d.ts +105 -0
  35. package/dist/terminal-view.d.ts.map +1 -0
  36. package/dist/terminal-view.js +350 -0
  37. package/dist/terminal-view.js.map +1 -0
  38. package/dist/tui.d.ts +11 -3
  39. package/dist/tui.d.ts.map +1 -1
  40. package/dist/tui.js +247 -185
  41. package/dist/tui.js.map +1 -1
  42. package/package.json +2 -2
package/dist/tui.js CHANGED
@@ -1,174 +1,275 @@
1
1
  import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { Box, render, Text, useInput } from "ink";
3
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { Box, render, Text, useInput, usePaste, useWindowSize } from "ink";
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
4
  import { compactChildRunText, formatApprovalDisplay, formatDelegationApproval, } from "./approval.js";
5
5
  import { formatObservabilityStatus } from "./observability-format.js";
6
- import { loopStateText } from "./render.js";
7
- /** 消息流中最多渲染的条数(全屏滚动近似) */
8
- const MAX_VISIBLE = 30;
6
+ import { formatArtifactReference, formatTerminalInput, formatTerminalRow, loopStateText, terminalText, } from "./render.js";
7
+ import { reduceTerminalInput, } from "./terminal-input.js";
8
+ import { createTerminalView, foldTerminalView } from "./terminal-view.js";
9
+ /** 认证错误不回显外部响应或原始异常,避免授权信息落入消息流。 */
10
+ export function formatMcpAuthenticationError(error) {
11
+ const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
12
+ if (code === "aborted")
13
+ return "登录已取消";
14
+ if (code === "run_timeout")
15
+ return "登录已超时,请重新发起";
16
+ if (code === "mcp_auth_required")
17
+ return "服务需要显式登录";
18
+ if (code === "mcp_auth_store_failed")
19
+ return "凭据存储失败";
20
+ return "认证失败,请检查服务配置后重试";
21
+ }
9
22
  /**
10
23
  * 全屏交互终端(ink):顶部标题栏 + 消息流(流式文本/工具调用可视化)+ 底部输入框。
11
24
  * 与 readline 模式共用同一 ChatSession 与事件流。
12
25
  */
13
- export function ChatTUI({ title, session, approvals, onExit }) {
14
- const [messages, updateMessages] = useState([]);
15
- const setMessages = useCallback((update) => {
16
- updateMessages((previous) => {
17
- const next = update(previous);
18
- if (next === previous || next.length <= MAX_VISIBLE)
19
- return next;
20
- // 仅额外保留尚未收到结果的工具消息,避免迟到结果失去显示绑定。
21
- return next.filter((message, index) => index >= next.length - MAX_VISIBLE ||
22
- message.tools.some((tool) => tool.isError === undefined && !tool.ended));
23
- });
26
+ export function ChatTUI({ title, session, approvals, onExit, mcp }) {
27
+ const [view, setView] = useState(createTerminalView);
28
+ const epoch = useRef(0);
29
+ const appendMessage = useCallback((role, text) => {
30
+ const action = { type: "append", epoch: epoch.current, role, text };
31
+ setView((previous) => foldTerminalView(previous, action));
24
32
  }, []);
25
- const [input, setInput] = useState("");
33
+ const [editing, setEditing] = useState({ draft: "", revision: 0 });
34
+ const editingRef = useRef(editing);
35
+ const input = editing.draft;
36
+ const approvalCommand = editing.approvalCommand?.text;
26
37
  const [busy, setBusy] = useState(false);
38
+ const busyRef = useRef(false);
39
+ const running = useRef(undefined);
40
+ const exiting = useRef(false);
27
41
  const [showHelp, setShowHelp] = useState(false);
28
42
  const [pendingApproval, setPendingApproval] = useState();
29
43
  const [lastRun, setLastRun] = useState();
30
44
  const [loopStatus, setLoopStatus] = useState();
31
- const idRef = useRef(0);
32
- // 键盘输入(受控输入框:字符累积 / 退格 / 回车发送)
33
- useInput((inputStr, key) => {
34
- if (pendingApproval) {
35
- if (inputStr.toLowerCase() === "y")
36
- approvals.resolve("allow");
37
- if (inputStr.toLowerCase() === "n" || key.return || key.escape)
38
- approvals.resolve("deny");
45
+ const windowSize = useWindowSize();
46
+ const login = useRef(undefined);
47
+ const mounted = useRef(true);
48
+ const [authorization, setAuthorization] = useState();
49
+ useEffect(() => {
50
+ mounted.current = true;
51
+ return () => {
52
+ mounted.current = false;
53
+ login.current?.controller.abort();
54
+ };
55
+ }, []);
56
+ const dispatchInput = (action) => {
57
+ if (exiting.current)
39
58
  return;
59
+ const current = { approvalId: approvals.current?.request.approvalId };
60
+ const next = reduceTerminalInput(editingRef.current, action, current);
61
+ editingRef.current = next.state;
62
+ setEditing(next.state);
63
+ for (const effect of next.effects) {
64
+ if (effect.type === "notice")
65
+ appendMessage("notice", effect.text);
66
+ else if (effect.type === "approval") {
67
+ if (approvals.current?.request.approvalId === effect.approvalId)
68
+ approvals.resolve(effect.decision);
69
+ }
70
+ else {
71
+ const command = effect.text.trim();
72
+ const control = /^\/(?:steer|follow-up)(?:\s|$)/u.test(command) ||
73
+ command === "/abort" ||
74
+ command === "/exit" ||
75
+ /^\/mcp\s+logout\s+\S+$/u.test(command);
76
+ if (effect.target === "approval-command" && !control) {
77
+ appendCommandError(new Error("审批期间使用 /steer 文本、/follow-up 文本、/abort 或 /exit;Esc 返回审批"));
78
+ continue;
79
+ }
80
+ if (busyRef.current && !control && command !== "/children")
81
+ continue;
82
+ if (login.current && !/^\/mcp(?:\s|$)/u.test(command) && command !== "/exit") {
83
+ appendAuthenticationNotice("登录等待中;使用 /mcp cancel 取消,或 /exit 退出;原稿已保留");
84
+ continue;
85
+ }
86
+ const submitted = reduceTerminalInput(editingRef.current, {
87
+ type: "submitted",
88
+ revision: effect.revision,
89
+ target: effect.target,
90
+ remember: effect.target === "draft" && !command.startsWith("/"),
91
+ }, current);
92
+ editingRef.current = submitted.state;
93
+ setEditing(submitted.state);
94
+ const operation = handleSubmit(effect.text);
95
+ if (busyRef.current && !control && command !== "/children")
96
+ running.current = operation;
97
+ }
40
98
  }
41
- if (key.return) {
42
- const command = input.trim();
43
- if (busy && command !== "/abort" && command !== "/children")
44
- return;
45
- void handleSubmit(input);
46
- setInput("");
47
- }
48
- else if (key.backspace) {
49
- setInput((v) => v.slice(0, -1));
50
- }
51
- else if (inputStr) {
52
- setInput((v) => v + inputStr);
53
- }
54
- });
99
+ };
100
+ useInput((text, key) => dispatchInput({ type: "key", text, key }));
101
+ usePaste((text) => dispatchInput({ type: "paste", text }));
55
102
  useEffect(() => approvals.subscribe(setPendingApproval), [approvals]);
56
103
  // 订阅会话事件:流式文本增量 + 工具调用实时状态
57
104
  useEffect(() => {
58
- const pushEvent = (event) => {
105
+ const pushEvent = (event, entry) => {
59
106
  if (event.type === "loop_state") {
60
107
  setLoopStatus(loopStateText(event.to, event.iteration, event.repairs));
61
108
  }
62
- if (!["agent_start", "text_delta", "tool_call", "tool_result"].includes(event.type))
63
- return;
64
- setMessages((prev) => {
65
- const next = [...prev];
66
- switch (event.type) {
67
- case "agent_start": {
68
- next.push({ id: idRef.current++, role: "assistant", text: "", tools: [] });
69
- break;
70
- }
71
- case "text_delta": {
72
- const last = next[next.length - 1];
73
- if (last && last.role === "assistant") {
74
- next[next.length - 1] = { ...last, text: last.text + event.delta };
75
- }
76
- break;
77
- }
78
- case "tool_call": {
79
- const last = next[next.length - 1];
80
- if (last && last.role === "assistant") {
81
- next[next.length - 1] = {
82
- ...last,
83
- tools: [
84
- ...last.tools,
85
- { tool: event.tool, args: event.args, callId: event.callId },
86
- ],
87
- };
88
- }
89
- break;
90
- }
91
- case "tool_result": {
92
- // 带身份的结果可晚于其他消息到达;旧事件仅匹配同名未完成调用。
93
- for (let index = next.length - 1; index >= 0; index--) {
94
- const message = next[index];
95
- const toolIndex = message.tools.findIndex((tool) => event.callId !== undefined
96
- ? tool.callId === event.callId
97
- : tool.tool === event.tool && tool.isError === undefined);
98
- if (toolIndex < 0)
99
- continue;
100
- next[index] = {
101
- ...message,
102
- tools: message.tools.map((tool, i) => i === toolIndex ? { ...tool, isError: event.isError } : tool),
103
- };
104
- break;
105
- }
106
- break;
107
- }
108
- default:
109
- break;
110
- }
111
- return next;
112
- });
109
+ const action = {
110
+ type: "event",
111
+ epoch: epoch.current,
112
+ event,
113
+ ...(entry ? { runId: entry.runId } : {}),
114
+ observedAtMs: performance.now(),
115
+ };
116
+ setView((previous) => foldTerminalView(previous, action));
113
117
  };
114
118
  return session.onEvent(pushEvent);
115
- }, [session, setMessages]);
119
+ }, [session]);
116
120
  const handleSubmit = async (text) => {
117
121
  const trimmed = text.trim();
118
122
  if (!trimmed)
119
123
  return;
124
+ if (trimmed === "/exit") {
125
+ exiting.current = true;
126
+ login.current?.controller.abort();
127
+ setAuthorization(undefined);
128
+ if (busyRef.current)
129
+ session.abort();
130
+ while (approvals.current)
131
+ approvals.resolve("deny");
132
+ await login.current?.operation;
133
+ // 运行错误由原提交处理;视图退出前仍须等待该次运行完成收尾。
134
+ await running.current?.catch(() => { });
135
+ onExit();
136
+ return;
137
+ }
138
+ if (/^\/mcp(?:\s|$)/u.test(trimmed)) {
139
+ if (trimmed === "/mcp cancel") {
140
+ login.current?.controller.abort();
141
+ setAuthorization(undefined);
142
+ return;
143
+ }
144
+ const command = /^\/mcp\s+(login|logout)\s+(\S+)$/u.exec(trimmed);
145
+ if (!command) {
146
+ appendCommandError(new Error("用法:/mcp login 服务、/mcp cancel、/mcp logout 服务"));
147
+ return;
148
+ }
149
+ const serverName = command[2];
150
+ const server = mcp?.config.mcp?.servers[serverName];
151
+ if (!mcp || server?.transport !== "streamable-http" || !server.oauth) {
152
+ appendCommandError(new Error("指定服务没有配置 OAuth 登录"));
153
+ return;
154
+ }
155
+ if (command[1] === "logout") {
156
+ login.current?.controller.abort();
157
+ setAuthorization(undefined);
158
+ try {
159
+ await mcp.authentication.logout(serverName);
160
+ appendAuthenticationNotice("已清除当前进程的服务凭据");
161
+ }
162
+ catch (error) {
163
+ appendCommandError(new Error(formatMcpAuthenticationError(error)));
164
+ }
165
+ return;
166
+ }
167
+ if (busy || pendingApproval || login.current) {
168
+ appendCommandError(new Error("请等待当前运行、审批或登录结束后再登录"));
169
+ return;
170
+ }
171
+ const controller = new AbortController();
172
+ setAuthorization({
173
+ target: `${serverName}:${server.url}`,
174
+ issuer: server.oauth.issuer,
175
+ scopes: server.oauth.scopes.join("、"),
176
+ });
177
+ const operation = mcp.authentication
178
+ .login(serverName, {
179
+ signal: controller.signal,
180
+ onAuthorization: (request, signal) => {
181
+ signal.throwIfAborted();
182
+ if (mounted.current)
183
+ setAuthorization((previous) => previous ? { ...previous, url: request.authorizationUrl } : previous);
184
+ },
185
+ })
186
+ .then(() => {
187
+ if (mounted.current)
188
+ appendAuthenticationNotice("登录成功,可继续提问");
189
+ }, (error) => {
190
+ if (mounted.current)
191
+ appendAuthenticationNotice(formatMcpAuthenticationError(error));
192
+ })
193
+ .finally(() => {
194
+ if (login.current?.controller === controller) {
195
+ login.current = undefined;
196
+ if (mounted.current)
197
+ setAuthorization(undefined);
198
+ }
199
+ });
200
+ login.current = { controller, operation };
201
+ return;
202
+ }
203
+ if (login.current) {
204
+ appendAuthenticationNotice("登录等待中;使用 /mcp cancel 取消,或 /exit 退出");
205
+ return;
206
+ }
120
207
  if (trimmed === "/abort") {
121
208
  session.abort();
209
+ while (approvals.current)
210
+ approvals.resolve("deny");
211
+ return;
212
+ }
213
+ const control = /^\/(steer|follow-up)(?:\s+([\s\S]*))?$/u.exec(trimmed);
214
+ if (control) {
215
+ const controlEpoch = epoch.current;
216
+ const message = control[2]?.trim();
217
+ if (!message) {
218
+ appendCommandError(new Error(`用法:/${control[1]} 文本`));
219
+ return;
220
+ }
221
+ try {
222
+ const receipt = await (control[1] === "steer"
223
+ ? session.steer(message)
224
+ : session.followUp(message));
225
+ setView((previous) => foldTerminalView(previous, { type: "control", epoch: controlEpoch, receipt }));
226
+ }
227
+ catch (error) {
228
+ appendCommandError(error);
229
+ }
122
230
  return;
123
231
  }
124
232
  if (trimmed === "/children") {
125
233
  try {
126
- const run = busy ? await session.inspectCurrentRunProjection() : lastRun;
234
+ const run = busyRef.current ? await session.inspectCurrentRunProjection() : lastRun;
127
235
  const text = run
128
236
  ? formatChildRuns(run)
129
- : busy
237
+ : busyRef.current
130
238
  ? "当前运行尚未产生 Child Run Projection。"
131
239
  : "尚未完成任何运行。";
132
- setMessages((prev) => [
133
- ...prev,
134
- { id: idRef.current++, role: "assistant", text, tools: [] },
135
- ]);
240
+ appendMessage("assistant", text);
136
241
  }
137
242
  catch (error) {
138
243
  appendCommandError(error);
139
244
  }
140
245
  return;
141
246
  }
142
- if (busy)
247
+ if (busyRef.current)
143
248
  return;
144
- if (trimmed === "/exit") {
145
- onExit();
146
- return;
147
- }
148
249
  if (trimmed === "/help") {
149
250
  setShowHelp((v) => !v);
150
251
  return;
151
252
  }
152
253
  if (trimmed === "/status") {
153
254
  const text = lastRun ? formatRunStatus(lastRun) : "尚未完成任何运行。";
154
- setMessages((prev) => [...prev, { id: idRef.current++, role: "assistant", text, tools: [] }]);
255
+ appendMessage("assistant", text);
155
256
  return;
156
257
  }
157
258
  if (trimmed === "/artifacts") {
158
259
  const text = formatArtifacts(lastRun);
159
- setMessages((prev) => [...prev, { id: idRef.current++, role: "assistant", text, tools: [] }]);
260
+ appendMessage("assistant", text);
160
261
  return;
161
262
  }
162
263
  if (trimmed === "/context") {
163
264
  const text = formatContext(lastRun);
164
- setMessages((prev) => [...prev, { id: idRef.current++, role: "assistant", text, tools: [] }]);
265
+ appendMessage("assistant", text);
165
266
  return;
166
267
  }
167
268
  if (trimmed === "/observability") {
168
269
  const text = lastRun
169
270
  ? formatObservabilityStatus(lastRun.observability)
170
271
  : "尚未完成任何运行。";
171
- setMessages((prev) => [...prev, { id: idRef.current++, role: "assistant", text, tools: [] }]);
272
+ appendMessage("assistant", text);
172
273
  return;
173
274
  }
174
275
  if (trimmed === "/checkpoints") {
@@ -178,7 +279,7 @@ export function ChatTUI({ title, session, approvals, onExit }) {
178
279
  : checkpoints
179
280
  .map((item) => `${item.checkpointId} · ${item.tool} · ${item.reversible ? "可恢复" : "不可自动恢复"}`)
180
281
  .join("\n");
181
- setMessages((prev) => [...prev, { id: idRef.current++, role: "assistant", text, tools: [] }]);
282
+ appendMessage("assistant", text);
182
283
  return;
183
284
  }
184
285
  if (trimmed.startsWith("/diff ")) {
@@ -189,10 +290,7 @@ export function ChatTUI({ title, session, approvals, onExit }) {
189
290
  ? `changed=${diff.changed}\n${diff.unifiedDiff ??
190
291
  `--- before\n${diff.beforeText ?? "(文件不存在)"}\n+++ after\n${diff.afterText ?? "(文件不存在)"}`}`
191
292
  : `不可自动比较:${diff.reason ?? "未知原因"}`;
192
- setMessages((prev) => [
193
- ...prev,
194
- { id: idRef.current++, role: "assistant", text, tools: [] },
195
- ]);
293
+ appendMessage("assistant", text);
196
294
  }
197
295
  catch (error) {
198
296
  appendCommandError(error);
@@ -203,108 +301,77 @@ export function ChatTUI({ title, session, approvals, onExit }) {
203
301
  const checkpointId = trimmed.slice("/restore ".length).trim();
204
302
  try {
205
303
  await session.restoreCheckpoint(checkpointId);
206
- setMessages((prev) => [
207
- ...prev,
208
- {
209
- id: idRef.current++,
210
- role: "assistant",
211
- text: `已恢复 checkpoint ${checkpointId}`,
212
- tools: [],
213
- },
214
- ]);
304
+ appendMessage("assistant", `已恢复 checkpoint ${checkpointId}`);
215
305
  }
216
306
  catch (error) {
217
307
  appendCommandError(error);
218
308
  }
219
309
  return;
220
310
  }
221
- setInput("");
222
- setMessages((prev) => [
223
- ...prev,
224
- { id: idRef.current++, role: "user", text: trimmed, tools: [] },
225
- ]);
311
+ const runEpoch = ++epoch.current;
312
+ setView((previous) => foldTerminalView(previous, { type: "begin", epoch: runEpoch }));
313
+ appendMessage("user", trimmed);
314
+ busyRef.current = true;
226
315
  setBusy(true);
227
316
  setLoopStatus(undefined);
317
+ let runId;
228
318
  try {
229
319
  const result = await session.chat(trimmed);
320
+ runId = result.run.runId;
230
321
  setLastRun(result.run);
231
322
  if (result.run.outcome.status !== "succeeded") {
232
- setMessages((prev) => [
233
- ...prev,
234
- {
235
- id: idRef.current++,
236
- role: "assistant",
237
- text: formatOutcomeDiagnostic(result.run),
238
- tools: [],
239
- },
240
- ]);
323
+ appendMessage("assistant", formatOutcomeDiagnostic(result.run));
241
324
  }
242
325
  }
243
326
  catch (error) {
244
- setMessages((prev) => [
245
- ...prev,
246
- {
247
- id: idRef.current++,
248
- role: "assistant",
249
- text: `运行失败:${error instanceof Error ? error.message : String(error)}`,
250
- tools: [],
251
- },
252
- ]);
327
+ appendMessage("assistant", `运行失败:${error instanceof Error ? error.message : String(error)}`);
253
328
  }
254
329
  finally {
255
- setMessages((previous) => previous.map((message) => ({
256
- ...message,
257
- tools: message.tools.map((tool) => tool.isError === undefined ? { ...tool, ended: true } : tool),
258
- })));
330
+ running.current = undefined;
331
+ setView((previous) => foldTerminalView(previous, { type: "end", epoch: runEpoch, ...(runId ? { runId } : {}) }));
332
+ busyRef.current = false;
259
333
  setBusy(false);
260
334
  }
261
335
  };
262
336
  const appendCommandError = (error) => {
263
- setMessages((prev) => [
264
- ...prev,
265
- {
266
- id: idRef.current++,
267
- role: "assistant",
268
- text: `命令失败:${error instanceof Error ? error.message : String(error)}`,
269
- tools: [],
270
- },
271
- ]);
337
+ appendMessage("notice", `命令失败:${error instanceof Error ? error.message : String(error)}`);
272
338
  };
273
- const visible = messages.slice(-MAX_VISIBLE);
339
+ const appendAuthenticationNotice = (text) => {
340
+ appendMessage("notice", text);
341
+ };
342
+ const visible = view.rows;
274
343
  const approvalDisplay = pendingApproval
275
344
  ? formatApprovalDisplay(pendingApproval.request)
276
345
  : undefined;
277
346
  const delegationApproval = pendingApproval
278
347
  ? formatDelegationApproval(pendingApproval.request)
279
348
  : undefined;
280
- return (_jsxs(Box, { flexDirection: "column", height: "100%", children: [_jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsxs(Text, { bold: true, color: "cyan", children: ["CoreMind \u00B7 ", title] }), _jsx(Text, { dimColor: true, children: " /help \u67E5\u770B\u547D\u4EE4 \u00B7 /exit \u9000\u51FA" })] }), _jsxs(Box, { flexDirection: "column", flexGrow: 1, paddingX: 1, children: [showHelp && (_jsx(Box, { marginY: 1, children: _jsx(Text, { color: "yellow", children: "/status \u72B6\u6001 \u00B7 /children \u5B50\u8FD0\u884C \u00B7 /artifacts \u4EA7\u7269 \u00B7 /context \u4E0A\u4E0B\u6587 \u00B7 /observability \u89C2\u6D4B \u00B7 /checkpoints \u5217\u8868 \u00B7 /diff ID \u00B7 /restore ID \u00B7 /exit \u00B7 /abort" }) })), visible.map((msg) => (_jsx(MessageRow, { msg: msg }, msg.id))), busy && _jsx(Text, { dimColor: true, children: loopStatus ? `↻ ${loopStatus}` : "…" })] }), pendingApproval && approvalDisplay && (_jsxs(Box, { borderStyle: "round", borderColor: "yellow", paddingX: 1, flexDirection: "column", children: [_jsx(Text, { color: "yellow", bold: true, children: delegationApproval
349
+ return (_jsxs(Box, { flexDirection: "column", height: "100%", width: windowSize.columns, children: [_jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsxs(Text, { bold: true, color: "cyan", children: ["CoreMind \u00B7 ", terminalText(title)] }), _jsx(Text, { dimColor: true, children: " /help \u67E5\u770B\u547D\u4EE4 \u00B7 /exit \u9000\u51FA" })] }), _jsxs(Box, { flexDirection: "column", flexGrow: 1, paddingX: 1, children: [showHelp && (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: "yellow", children: ["/status \u72B6\u6001 \u00B7 /children \u5B50\u8FD0\u884C \u00B7 /artifacts \u4EA7\u7269 \u00B7 /context \u4E0A\u4E0B\u6587 \u00B7 /observability \u89C2\u6D4B \u00B7 /checkpoints \u5217\u8868 \u00B7 /diff ID \u00B7 /restore ID \u00B7 /exit \u00B7 /abort", "\n", "/steer \u6587\u672C\uFF1A\u8FFD\u52A0\u6307\u4EE4 \u00B7 /follow-up \u6587\u672C\uFF1A\u4EFB\u52A1\u81EA\u7136\u7ED3\u675F\u540E\u7EE7\u7EED", "\n", "/mcp login \u670D\u52A1 \u00B7 /mcp cancel \u00B7 /mcp logout \u670D\u52A1\uFF08\u51ED\u636E\u4EC5\u5F53\u524D\u8FDB\u7A0B\u4FDD\u5B58\uFF09", "\n", "applied \u4EC5\u8868\u793A\u5DF2\u4EA4\u961F\u5217\uFF1B\u8F93\u5165\u7684 claimed/completed/discarded \u5355\u72EC\u663E\u793A\u3002", "\n", "\u2190/\u2192 \u79FB\u52A8 \u00B7 Home/End \u6574\u7A3F\u9996\u5C3E \u00B7 \u2191/\u2193 \u5386\u53F2\uFF0C\u2193 \u8FD4\u56DE\u8349\u7A3F\u3002"] }) })), visible.map((row) => (_jsx(MessageRow, { row: row }, row.id))), busy && _jsx(Text, { dimColor: true, children: loopStatus ? `↻ ${loopStatus}` : "…" })] }), authorization && (_jsxs(Box, { borderStyle: "round", borderColor: "yellow", paddingX: 1, flexDirection: "column", children: [_jsxs(Text, { children: ["\u767B\u5F55 ", terminalText(authorization.target)] }), _jsxs(Text, { children: ["\u6388\u6743\u65B9\uFF1A", terminalText(authorization.issuer), " \u00B7 \u8303\u56F4\uFF1A", terminalText(authorization.scopes)] }), _jsx(Text, { children: authorization.url ?? "正在准备授权链接…" }), _jsx(Text, { children: "\u8BF7\u624B\u52A8\u6253\u5F00\u94FE\u63A5\uFF1B/mcp cancel \u53D6\u6D88 \u00B7 /exit \u9000\u51FA\uFF1B\u51ED\u636E\u4EC5\u5F53\u524D\u8FDB\u7A0B\u4FDD\u5B58" })] })), pendingApproval && approvalDisplay && (_jsxs(Box, { borderStyle: "round", borderColor: "yellow", paddingX: 1, flexDirection: "column", children: [_jsx(Text, { color: "yellow", bold: true, children: delegationApproval
281
350
  ? `Child Run 委派审批:${delegationApproval.target}`
282
- : `权限审批:${pendingApproval.request.tool}(${pendingApproval.request.risk})` }), delegationApproval ? (_jsxs(_Fragment, { children: [_jsxs(Text, { children: ["\u4EFB\u52A1\uFF1A", delegationApproval.task] }), _jsxs(Text, { children: ["\u9884\u7B97\uFF1A", delegationApproval.budget] }), _jsxs(Text, { children: ["\u5C42\u7EA7\uFF1A", delegationApproval.hierarchy] }), _jsxs(Text, { children: ["\u5F15\u7528\uFF1A", delegationApproval.references] }), _jsx(Text, { children: "\u6388\u6743\uFF1A\u4EC5\u521B\u5EFA Child Run\uFF1B\u5B50\u7EA7\u5DE5\u5177\u4E0E\u5916\u90E8\u526F\u4F5C\u7528\u4ECD\u9700\u72EC\u7ACB\u5BA1\u6279" })] })) : (_jsxs(_Fragment, { children: [_jsxs(Text, { children: ["\u526F\u4F5C\u7528\uFF1A", approvalDisplay.effect] }), _jsxs(Text, { children: ["\u76EE\u6807\uFF1A", approvalDisplay.targets] }), _jsxs(Text, { children: ["\u53C2\u6570\uFF1A", approvalDisplay.arguments] })] })), _jsxs(Text, { children: ["\u539F\u56E0\uFF1A", approvalDisplay.reason] }), _jsx(Text, { children: "[y] \u5141\u8BB8 \u00B7 [n/Enter] \u62D2\u7EDD" })] })), lastRun && (_jsx(Box, { paddingX: 1, children: _jsx(Text, { dimColor: true, children: formatRunStatus(lastRun) }) })), _jsxs(Box, { borderStyle: "round", paddingX: 1, children: [_jsx(Text, { color: "green", children: "\u4F60 > " }), _jsx(Text, { children: input })] })] }));
351
+ : `权限审批:${pendingApproval.request.tool}(${pendingApproval.request.risk})` }), _jsxs(Text, { children: ["\u5BA1\u6279 ", terminalText(pendingApproval.request.approvalId), " \u00B7", " ", pendingApproval.request.callId
352
+ ? `${terminalText(pendingApproval.request.agent)}/${terminalText(pendingApproval.request.stepId ?? "-")}/${terminalText(pendingApproval.request.callId)}`
353
+ : "未绑定调用"] }), delegationApproval ? (_jsxs(_Fragment, { children: [_jsxs(Text, { children: ["\u4EFB\u52A1\uFF1A", delegationApproval.task] }), _jsxs(Text, { children: ["\u9884\u7B97\uFF1A", delegationApproval.budget] }), _jsxs(Text, { children: ["\u5C42\u7EA7\uFF1A", delegationApproval.hierarchy] }), _jsxs(Text, { children: ["\u5F15\u7528\uFF1A", delegationApproval.references] }), _jsx(Text, { children: "\u6388\u6743\uFF1A\u4EC5\u521B\u5EFA Child Run\uFF1B\u5B50\u7EA7\u5DE5\u5177\u4E0E\u5916\u90E8\u526F\u4F5C\u7528\u4ECD\u9700\u72EC\u7ACB\u5BA1\u6279" })] })) : (_jsxs(_Fragment, { children: [_jsxs(Text, { children: ["\u526F\u4F5C\u7528\uFF1A", approvalDisplay.effect] }), _jsxs(Text, { children: ["\u76EE\u6807\uFF1A", approvalDisplay.targets] }), _jsxs(Text, { children: ["\u53C2\u6570\uFF1A", approvalDisplay.arguments] })] })), _jsxs(Text, { children: ["\u539F\u56E0\uFF1A", approvalDisplay.reason] }), _jsx(Text, { children: "[y] \u5141\u8BB8 \u00B7 [n/Enter] \u62D2\u7EDD \u00B7 [/] \u8F93\u5165\u63A7\u5236\u547D\u4EE4\uFF0CEsc \u8FD4\u56DE\u5BA1\u6279" })] })), lastRun && (_jsx(Box, { paddingX: 1, children: _jsx(Text, { dimColor: true, children: formatRunStatus(lastRun) }) })), _jsxs(Box, { borderStyle: "round", paddingX: 1, children: [_jsx(Text, { color: "green", children: "\u4F60 > " }), _jsx(Text, { children: pendingApproval || approvalCommand !== undefined
354
+ ? terminalText(input)
355
+ : formatTerminalInput(input, editing.cursor) })] }), approvalCommand !== undefined && (_jsx(Box, { paddingX: 1, children: _jsxs(Text, { children: ["\u63A7\u5236\u547D\u4EE4 > ", formatTerminalInput(approvalCommand, editing.approvalCommand?.cursor)] }) })), busy && (_jsx(Text, { dimColor: true, children: "\u666E\u901A\u8F93\u5165\u4FDD\u7559\u4E3A\u8349\u7A3F\uFF1B/steer \u8FFD\u52A0\u6307\u4EE4 \u00B7 /follow-up \u540E\u7EED\u8F93\u5165 \u00B7 /abort \u4E2D\u6B62" })), !busy && _jsxs(Text, { dimColor: true, children: ["\u8F93\u5165\u5C31\u7EEA", input ? ",按 Enter 发送草稿" : ""] })] }));
283
356
  }
284
- function MessageRow({ msg }) {
285
- // 工具行 key:同名工具按出现次数计数(避免数组索引作 key)
286
- const toolViews = useMemo(() => {
287
- const seen = {};
288
- return msg.tools.map((tool) => {
289
- seen[tool.tool] = (seen[tool.tool] ?? 0) + 1;
290
- return { tool, key: `${tool.tool}-${seen[tool.tool]}` };
291
- });
292
- }, [msg.tools]);
293
- return (_jsx(Box, { flexDirection: "column", marginBottom: 0, children: msg.role === "user" ? (_jsxs(Text, { color: "green", children: ["\u4F60 > ", msg.text] })) : (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "cyan", children: "[assistant]" }), _jsxs(Box, { paddingLeft: 2, flexDirection: "column", children: [_jsx(Text, { children: msg.text }), toolViews.map(({ tool, key }) => (_jsxs(Text, { dimColor: true, children: ["\u2699 ", tool.tool, tool.isError === undefined
294
- ? tool.ended
295
- ? " ?"
296
- : " …"
297
- : tool.isError
298
- ? " ✗"
299
- : " ✓"] }, key)))] })] })) }));
357
+ function MessageRow({ row }) {
358
+ return (_jsx(Box, { flexDirection: "column", marginBottom: 0, children: _jsx(Text, { color: row.kind === "text" && row.role === "user" ? "green" : undefined, children: formatTerminalRow(row) }) }));
300
359
  }
301
360
  /** 运行全屏 TUI(渲染并等待退出) */
302
- export function runChatTUI(session, title, approvals) {
303
- return new Promise((resolve) => {
304
- const app = render(_jsx(ChatTUI, { title: title, session: session, approvals: approvals, onExit: () => {
361
+ export function runChatTUI(session, title, approvals, mcp) {
362
+ return new Promise((resolve, reject) => {
363
+ const app = render(_jsx(ChatTUI, { title: title, session: session, approvals: approvals, mcp: mcp, onExit: () => {
305
364
  app.unmount();
306
365
  resolve();
307
366
  } }));
367
+ const onEnd = () => app.unmount();
368
+ process.stdin.once("end", onEnd);
369
+ void app
370
+ .waitUntilExit()
371
+ .then(() => resolve(), reject)
372
+ .finally(() => {
373
+ process.stdin.off("end", onEnd);
374
+ });
308
375
  });
309
376
  }
310
377
  export function formatRunStatus(run) {
@@ -380,12 +447,7 @@ function formatArtifacts(run) {
380
447
  const artifacts = run.snapshot.artifacts;
381
448
  if (artifacts.length === 0)
382
449
  return "本轮没有 Artifact。";
383
- return artifacts
384
- .map((artifact) => {
385
- const location = artifact.relativePath ?? "未保存";
386
- return `${artifact.artifactId} · ${artifact.status} · ${artifact.sizeBytes} bytes · ${location}`;
387
- })
388
- .join("\n");
450
+ return `本轮 Artifact:\n${artifacts.map(formatArtifactReference).join("\n")}`;
389
451
  }
390
452
  function formatContext(run) {
391
453
  if (!run)