lemma-agent 0.0.0-stage → 1.0.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/README.md +121 -2
- package/bin/lemma.mjs +42 -0
- package/dist/acceptance.js +63 -0
- package/dist/admin.js +1482 -0
- package/dist/agents.js +245 -0
- package/dist/api-member.js +537 -0
- package/dist/app.js +161 -0
- package/dist/board.js +185 -0
- package/dist/business-tools.js +153 -0
- package/dist/change-ops.js +91 -0
- package/dist/changes.js +46 -0
- package/dist/cli-runner.js +106 -0
- package/dist/code-tools.js +396 -0
- package/dist/coding-benchmark-fixtures.js +1049 -0
- package/dist/coding-benchmark-suite.js +1252 -0
- package/dist/collaboration-benchmark.js +349 -0
- package/dist/config.js +392 -0
- package/dist/context-benchmark.js +91 -0
- package/dist/conventions.js +282 -0
- package/dist/conversation.js +39 -0
- package/dist/credentials.js +44 -0
- package/dist/deliverables.js +43 -0
- package/dist/digest.js +129 -0
- package/dist/dispatch.js +801 -0
- package/dist/execution-settings.js +24 -0
- package/dist/git-workbench.js +800 -0
- package/dist/git.js +149 -0
- package/dist/integration-git.js +108 -0
- package/dist/integrations.js +557 -0
- package/dist/jobs.js +100 -0
- package/dist/lead.js +263 -0
- package/dist/learning.js +36 -0
- package/dist/main.js +1402 -0
- package/dist/mcp-settings.js +45 -0
- package/dist/mcp-tools.js +102 -0
- package/dist/member-settings.js +245 -0
- package/dist/model-selection.js +48 -0
- package/dist/models.js +145 -0
- package/dist/native-selectors.js +45 -0
- package/dist/native-terminal-components.js +100 -0
- package/dist/ood-benchmark.js +660 -0
- package/dist/operations.js +21 -0
- package/dist/printer.js +113 -0
- package/dist/repair.js +102 -0
- package/dist/resources.js +31 -0
- package/dist/result-summary.js +8 -0
- package/dist/results.js +41 -0
- package/dist/scope.js +114 -0
- package/dist/sessions.js +95 -0
- package/dist/settings.js +30 -0
- package/dist/task-commands.js +37 -0
- package/dist/task-lifecycle.js +49 -0
- package/dist/task-readiness.js +22 -0
- package/dist/task-recovery.js +116 -0
- package/dist/task-review.js +70 -0
- package/dist/task-workflow.js +424 -0
- package/dist/terminal-layout.js +27 -0
- package/dist/terminal-state.js +145 -0
- package/dist/terminal.js +800 -0
- package/dist/tool-settings.js +111 -0
- package/dist/tools.js +1043 -0
- package/dist/ux-telemetry.js +127 -0
- package/dist/view.js +114 -0
- package/package.json +79 -6
- package/web/index.html +136 -0
- package/web/js/conversations.js +312 -0
- package/web/js/dag.js +495 -0
- package/web/js/drawer.js +139 -0
- package/web/js/editors.js +424 -0
- package/web/js/gitlens.js +844 -0
- package/web/js/main.js +152 -0
- package/web/js/sankey.js +476 -0
- package/web/js/store.js +291 -0
- package/web/js/ticket.js +151 -0
- package/web/js/timeline.js +183 -0
- package/web/js/topology.js +454 -0
- package/web/js/util.js +232 -0
- package/web/js/views.js +1496 -0
- package/web/style.css +5299 -0
package/dist/main.js
ADDED
|
@@ -0,0 +1,1402 @@
|
|
|
1
|
+
// 入口(终端是主体,后台网页随终端一起启动):
|
|
2
|
+
// npm start 真实模型 + 新版终端 + 后台网页 http://127.0.0.1:8787
|
|
3
|
+
// npm start -- "你的问题" 单次提问,答完退出(不开后台)
|
|
4
|
+
// npm run tui 新版终端,真实模型;--plain 回到普通模式
|
|
5
|
+
// --no-web 不开后台网页
|
|
6
|
+
import { resolve } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { clearLine, createInterface, cursorTo } from "node:readline";
|
|
10
|
+
import { Writable } from "node:stream";
|
|
11
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
12
|
+
import { LiveDoc } from "@earendil-works/pi-durable";
|
|
13
|
+
import { startAdmin } from "./admin.js";
|
|
14
|
+
import { Board, boardTasks, STATUS_LABEL } from "./board.js";
|
|
15
|
+
import { applyChange, cleanChanges, dropChange, pendingChanges } from "./change-ops.js";
|
|
16
|
+
import { initRules, scanConventions, syncRules } from "./conventions.js";
|
|
17
|
+
import { openApp } from "./app.js";
|
|
18
|
+
import { loadConfig, sameConfigRepoRoot } from "./config.js";
|
|
19
|
+
import { memberSettingsCommand, MEMBER_HELP } from "./member-settings.js";
|
|
20
|
+
import { clip, Jobs } from "./jobs.js";
|
|
21
|
+
import { createOrchestratorModel, orchestratorKeyWarning } from "./models.js";
|
|
22
|
+
import { controllerModels, nativeModelCatalog, selectControllerModel, restoreControllerModel } from "./model-selection.js";
|
|
23
|
+
import { colors as c, follow, setOutputSink, writeLine as log } from "./printer.js";
|
|
24
|
+
import { AgentSessions, RunBudget } from "./dispatch.js";
|
|
25
|
+
import { Learning } from "./learning.js";
|
|
26
|
+
import { Results, resultPage } from "./results.js";
|
|
27
|
+
import { Operations, operationList, resolveOperation } from "./operations.js";
|
|
28
|
+
import { CostLedger, Resources, resourceSnapshot } from "./resources.js";
|
|
29
|
+
import { resultExcerpt } from "./deliverables.js";
|
|
30
|
+
import { taskCommand, TASK_HELP } from "./task-commands.js";
|
|
31
|
+
import { AgentTerminal } from "./terminal.js";
|
|
32
|
+
import { readyTasks, taskReadiness } from "./task-readiness.js";
|
|
33
|
+
import { Integrations, integrationSummary } from "./integrations.js";
|
|
34
|
+
import { listNativeConversations, watchTerminalState } from "./terminal-state.js";
|
|
35
|
+
import { SessionCatalog } from "./sessions.js";
|
|
36
|
+
import { liveDigest, storedDigest } from "./digest.js";
|
|
37
|
+
export async function startMain(overrides) {
|
|
38
|
+
const context = BACKGROUND_CONTEXT;
|
|
39
|
+
const argv = process.argv.slice(2);
|
|
40
|
+
const flags = new Set(argv.filter((a) => a.startsWith("--")));
|
|
41
|
+
const configPath = resolve(process.env.PI_AGENT_CONFIG ?? "pi-agent.config.json");
|
|
42
|
+
const baseConfig = loadConfig(configPath);
|
|
43
|
+
const sessionCatalog = new SessionCatalog(overrides?.config ? overrides.config(baseConfig) : baseConfig);
|
|
44
|
+
let sessionId = argv.find((a) => a.startsWith("--session="))?.slice(10) ?? sessionCatalog.selected();
|
|
45
|
+
if (sessionId !== "default" && !sessionCatalog.list().some((s) => s.id === sessionId))
|
|
46
|
+
sessionCatalog.create(sessionId);
|
|
47
|
+
let config = sessionCatalog.config(sessionId);
|
|
48
|
+
let orchestrator = overrides?.createOrchestrator ? overrides.createOrchestrator(config) : createOrchestratorModel(config.orchestrator, `${config.storage}.models.json`);
|
|
49
|
+
let app = await openApp(config, orchestrator, context).catch((error) => {
|
|
50
|
+
console.error(`启动失败:${error.message}`);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
});
|
|
53
|
+
let { harness, root, agents } = app;
|
|
54
|
+
sessionCatalog.select(sessionId);
|
|
55
|
+
const sessions = new Map([[sessionId, { app, config, orchestrator }]]);
|
|
56
|
+
const drafts = new Map();
|
|
57
|
+
overrides?.onOrchestrator?.(orchestrator);
|
|
58
|
+
let stopFollowing = async () => { };
|
|
59
|
+
let terminalUI;
|
|
60
|
+
let terminalConversation;
|
|
61
|
+
let terminalGeneration = 0;
|
|
62
|
+
let terminalCommands = Promise.resolve();
|
|
63
|
+
let activeTerminalCommands = 0;
|
|
64
|
+
let stopTerminalStatus = () => { };
|
|
65
|
+
const terminalDraftKey = () => `${sessionId}:${terminalConversation?.id ?? root.id}`;
|
|
66
|
+
// 后台派工的实时输出:带上编号打印,提示符跟着重画
|
|
67
|
+
function attachJobOutput(id, target) {
|
|
68
|
+
target.jobs.on("output", (job, line) => {
|
|
69
|
+
if (id !== sessionId || closing || terminalUI)
|
|
70
|
+
return;
|
|
71
|
+
// 先擦掉当前的提示符行再打印;终端空闲时再把提示符(和已经输入的内容)画回来
|
|
72
|
+
clearPromptLine();
|
|
73
|
+
log(c.dim(` [${id === sessionId ? job : `${id}/${job}`}] ${line}`));
|
|
74
|
+
if (replIdle())
|
|
75
|
+
rl?.prompt(true);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
let applyConfirmQueue = Promise.resolve();
|
|
79
|
+
function attachSessionHandlers(id, target) {
|
|
80
|
+
attachJobOutput(id, target);
|
|
81
|
+
target.confirmApply = (req) => {
|
|
82
|
+
const run = async () => {
|
|
83
|
+
if (id !== sessionId || closing)
|
|
84
|
+
return { approvedIds: [], deferred: true, reason: "当前不在该交互会话中。" };
|
|
85
|
+
if (terminalUI) {
|
|
86
|
+
const decision = await terminalUI.confirmApply(req);
|
|
87
|
+
if (decision.approvedIds.length)
|
|
88
|
+
log(c.cyan(`已确认合并:${decision.approvedIds.map((x) => `#${x}`).join("、")}`));
|
|
89
|
+
return decision;
|
|
90
|
+
}
|
|
91
|
+
if (rl && process.stdin.isTTY) {
|
|
92
|
+
log(c.cyan("\n⚑ 请求确认合并改动到工作区:"));
|
|
93
|
+
if (req.summary)
|
|
94
|
+
log(c.yellow(` ${req.summary}`));
|
|
95
|
+
for (const item of req.items)
|
|
96
|
+
log(` • #${item.id} (${item.isIntegration ? "联合集成" : item.agent}) ${item.filesCount} 文件 +${item.add} −${item.del} — ${item.task}`);
|
|
97
|
+
try {
|
|
98
|
+
const answer = (await settingQuestion({ title: "同意全部合并请输入 y(留空或 n 暂不合并)" })).trim().toLowerCase();
|
|
99
|
+
return { approvedIds: answer === "y" || answer === "yes" ? req.items.map((x) => x.id) : [] };
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return { approvedIds: [] };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { approvedIds: [], deferred: true, reason: "当前没有交互终端可弹窗确认。" };
|
|
106
|
+
};
|
|
107
|
+
const queued = applyConfirmQueue.then(run, run);
|
|
108
|
+
applyConfirmQueue = queued.catch(() => { });
|
|
109
|
+
return queued;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
attachSessionHandlers(sessionId, app);
|
|
113
|
+
let rl;
|
|
114
|
+
/** 先光标回行首再清整行:草稿在行尾时,先 clearLine 只会清掉光标右侧的空内容,所以要回行首再清 */
|
|
115
|
+
function clearPromptLine() {
|
|
116
|
+
if (rl && process.stdout.isTTY) {
|
|
117
|
+
cursorTo(process.stdout, 0);
|
|
118
|
+
clearLine(process.stdout, 0);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** 终端在等你输入(没有在等总调度回答) */
|
|
122
|
+
let replIdle = () => false;
|
|
123
|
+
let admin;
|
|
124
|
+
let webPort;
|
|
125
|
+
let closing = false;
|
|
126
|
+
let switchingSession = false;
|
|
127
|
+
let configuring = false;
|
|
128
|
+
let plainQuestion;
|
|
129
|
+
async function assertConfigIdle() {
|
|
130
|
+
if (closing || switchingSession)
|
|
131
|
+
throw new Error("正在切换或退出,请稍后配置。");
|
|
132
|
+
if (terminalConversation && String(terminalConversation.id) !== String(root.id))
|
|
133
|
+
throw new Error("请先 /main 返回总控再配置成员。");
|
|
134
|
+
for (const runtime of sessions.values()) {
|
|
135
|
+
const state = await runtime.app.harness.inspect(context);
|
|
136
|
+
if (state.tasks.length || state.submissions.length)
|
|
137
|
+
throw new Error("有会话正在执行任务,请先等待完成或 /abort all,再修改团队配置。");
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function settingQuestion(input) {
|
|
141
|
+
if (terminalUI)
|
|
142
|
+
return terminalUI.question(input);
|
|
143
|
+
if (!rl)
|
|
144
|
+
throw new Error("请在交互终端中执行配置命令。");
|
|
145
|
+
if (input.secret && !process.stdin.isTTY)
|
|
146
|
+
throw new Error("密钥输入需要交互终端;请用 npm start,或预先设置凭据环境变量。");
|
|
147
|
+
log(`${input.title}${input.value ? `(留空保留:${input.value})` : ""}`);
|
|
148
|
+
return new Promise((resolve, reject) => { plainQuestion = { resolve, reject, secret: !!input.secret }; });
|
|
149
|
+
}
|
|
150
|
+
async function commitSettings(draft, next, controller) {
|
|
151
|
+
await assertConfigIdle();
|
|
152
|
+
// Stage registry/model changes first; no Harness or session database is replaced.
|
|
153
|
+
const targets = [...sessions.values()].map((runtime) => {
|
|
154
|
+
const candidate = {
|
|
155
|
+
...runtime.config,
|
|
156
|
+
agents: next.agents,
|
|
157
|
+
roles: next.roles,
|
|
158
|
+
collaboration: next.collaboration,
|
|
159
|
+
execution: next.execution,
|
|
160
|
+
budget: next.budget,
|
|
161
|
+
autonomy: sameConfigRepoRoot(runtime.config.workdir, next) ? next.autonomy : { ...next.autonomy, checks: [] },
|
|
162
|
+
...(controller ? { orchestrator: next.orchestrator } : {}),
|
|
163
|
+
};
|
|
164
|
+
const model = controller ? createOrchestratorModel(next.orchestrator, `${runtime.config.storage}.models.json`) : undefined;
|
|
165
|
+
return { runtime, candidate, model, apply: runtime.app.prepareMembers(candidate) };
|
|
166
|
+
});
|
|
167
|
+
draft.save();
|
|
168
|
+
for (const target of targets) {
|
|
169
|
+
if (target.model) {
|
|
170
|
+
// Keep the original Models object referenced by Harness and native selectors.
|
|
171
|
+
const provider = target.model.models.getProvider(target.model.ref.provider);
|
|
172
|
+
if (!provider)
|
|
173
|
+
throw new Error("总控模型目录未注册。");
|
|
174
|
+
target.runtime.orchestrator.models.setProvider(provider);
|
|
175
|
+
Object.assign(target.runtime.orchestrator, { ...target.model, models: target.runtime.orchestrator.models });
|
|
176
|
+
await restoreControllerModel(target.runtime.app.harness, target.runtime.app.root, target.runtime.orchestrator.models, target.model.ref, context);
|
|
177
|
+
}
|
|
178
|
+
target.apply();
|
|
179
|
+
}
|
|
180
|
+
Object.assign(baseConfig, next);
|
|
181
|
+
({ app, config, orchestrator } = sessions.get(sessionId));
|
|
182
|
+
({ harness, root, agents } = app);
|
|
183
|
+
await startWeb();
|
|
184
|
+
if (controller)
|
|
185
|
+
terminalUI?.setModel(`${orchestrator.ref.provider}/${orchestrator.ref.modelId}`);
|
|
186
|
+
}
|
|
187
|
+
async function conversationList() {
|
|
188
|
+
return Promise.all(sessionCatalog.list().map(async (info) => {
|
|
189
|
+
const runtime = sessions.get(info.id);
|
|
190
|
+
const live = runtime ? await runtime.app.harness.snapshot(LiveDoc, runtime.app.root.id, context) : undefined;
|
|
191
|
+
const jobs = runtime ? await runtime.app.harness.snapshot(Jobs, context) : undefined;
|
|
192
|
+
const digest = runtime ? await liveDigest(runtime.app.harness, runtime.app.root, info.storage) : await storedDigest(info.id, info.storage);
|
|
193
|
+
return { id: info.id, title: info.title, named: info.title !== info.id, digest, createdAt: info.createdAt, workdir: info.workdir,
|
|
194
|
+
current: info.id === sessionId, opened: !!runtime, controllerId: runtime ? String(runtime.app.root.id) : null,
|
|
195
|
+
busy: live?.run !== undefined, runningJobs: Object.values(jobs?.jobs ?? {}).filter((j) => j.status === "running").length };
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
async function startWeb() {
|
|
199
|
+
if (!config.web.enabled || flags.has("--no-web"))
|
|
200
|
+
return;
|
|
201
|
+
const port = webPort ?? Number(process.env.PI_AGENT_PORT ?? config.web.port);
|
|
202
|
+
const options = {
|
|
203
|
+
app, config, configPath, orchestrator, port, context,
|
|
204
|
+
session: { id: sessionId, title: sessionCatalog.get(sessionId).title, controllerId: String(root.id) },
|
|
205
|
+
settings: {
|
|
206
|
+
path: configPath,
|
|
207
|
+
config: () => config,
|
|
208
|
+
assertIdle: assertConfigIdle,
|
|
209
|
+
commit: commitSettings,
|
|
210
|
+
},
|
|
211
|
+
conversations: {
|
|
212
|
+
list: conversationList,
|
|
213
|
+
busy: () => switchingSession || configuring || closing || activeTerminalCommands > 0,
|
|
214
|
+
async create(title) {
|
|
215
|
+
const label = title.trim() || `新对话 ${new Date().toLocaleString("zh-CN")}`;
|
|
216
|
+
if (label.length > 120)
|
|
217
|
+
throw new Error("对话标题不能超过 120 个字符");
|
|
218
|
+
const info = sessionCatalog.create(`c-${randomUUID().slice(0, 12)}`, config.workdir);
|
|
219
|
+
sessionCatalog.rename(info.id, label);
|
|
220
|
+
return { id: info.id };
|
|
221
|
+
},
|
|
222
|
+
select: (id) => sessionCommand(`/session use ${id}`),
|
|
223
|
+
async rename(id, title) {
|
|
224
|
+
sessionCatalog.rename(id, title);
|
|
225
|
+
if (id === sessionId && admin)
|
|
226
|
+
log(`网页已重命名当前对话:${title}`);
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
notify: (line) => { clearPromptLine(); log(c.yellow(`\n[${line}]`)); rl?.prompt(true); },
|
|
230
|
+
};
|
|
231
|
+
if (admin)
|
|
232
|
+
await admin.rebind(options);
|
|
233
|
+
else
|
|
234
|
+
admin = await startAdmin(options).catch((error) => { log(c.red(`后台网页没能启动:${error.message}(终端照常可用)`)); return undefined; });
|
|
235
|
+
if (admin)
|
|
236
|
+
webPort = Number(new URL(admin.url).port);
|
|
237
|
+
}
|
|
238
|
+
async function sessionCommand(line) {
|
|
239
|
+
if (configuring)
|
|
240
|
+
throw new Error("正在配置,请完成或取消配置后再切换会话。");
|
|
241
|
+
const [, action = "list", suppliedId = "", ...rest] = line.split(/\s+/);
|
|
242
|
+
const id = action === "new" && !suppliedId ? `s-${Date.now().toString(36)}` : suppliedId;
|
|
243
|
+
if (action === "list" || !action) {
|
|
244
|
+
for (const info of sessionCatalog.list()) {
|
|
245
|
+
const runtime = sessions.get(info.id);
|
|
246
|
+
const live = runtime ? await runtime.app.harness.snapshot(LiveDoc, runtime.app.root.id, context) : undefined;
|
|
247
|
+
const doc = runtime ? await runtime.app.harness.snapshot(Jobs, context) : undefined;
|
|
248
|
+
const jobs = Object.values(doc?.jobs ?? {}).filter((j) => j.status === "running").length;
|
|
249
|
+
log(`${info.id === sessionId ? "●" : "○"} ${info.id} · ${info.title} · 总控对话 ${runtime ? String(runtime.app.root.id) : "打开后显示"} · ${live?.run ? "运行中" : runtime ? "已打开" : "未打开"} · 后台 ${jobs} · ${info.workdir}`);
|
|
250
|
+
}
|
|
251
|
+
log("/session new <编号> [项目路径] · /session use <编号> · /session rename <编号> <标题>;切换不会中止其他会话。");
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (action === "rename") {
|
|
255
|
+
sessionCatalog.rename(id, rest.join(" "));
|
|
256
|
+
log(`已重命名 ${id}。`);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (action !== "new" && action !== "use")
|
|
260
|
+
throw new Error("用法:/sessions 或 /session new|use|rename <编号>");
|
|
261
|
+
if (activeTerminalCommands)
|
|
262
|
+
throw new Error("当前控制命令尚未完成,请稍后再切换会话。");
|
|
263
|
+
if (switchingSession)
|
|
264
|
+
throw new Error("正在切换会话,请稍后。");
|
|
265
|
+
switchingSession = true;
|
|
266
|
+
try {
|
|
267
|
+
if (action === "new")
|
|
268
|
+
sessionCatalog.create(id, rest.join(" ").replace(/^"|"$/g, "") || config.workdir);
|
|
269
|
+
if (id === sessionId)
|
|
270
|
+
return;
|
|
271
|
+
let runtime = sessions.get(id);
|
|
272
|
+
if (!runtime) {
|
|
273
|
+
const nextConfig = sessionCatalog.config(id);
|
|
274
|
+
const nextModel = overrides?.createOrchestrator ? overrides.createOrchestrator(nextConfig) : createOrchestratorModel(nextConfig.orchestrator, `${nextConfig.storage}.models.json`);
|
|
275
|
+
const nextApp = await openApp(nextConfig, nextModel, context);
|
|
276
|
+
overrides?.onOrchestrator?.(nextModel);
|
|
277
|
+
runtime = { app: nextApp, config: nextConfig, orchestrator: nextModel };
|
|
278
|
+
sessions.set(id, runtime);
|
|
279
|
+
attachSessionHandlers(id, nextApp);
|
|
280
|
+
}
|
|
281
|
+
const wasTui = !!terminalUI;
|
|
282
|
+
if (terminalUI)
|
|
283
|
+
drafts.set(terminalDraftKey(), terminalUI.editor.getExpandedText());
|
|
284
|
+
terminalGeneration++;
|
|
285
|
+
stopTerminalStatus();
|
|
286
|
+
await stopFollowing();
|
|
287
|
+
const previousId = sessionId;
|
|
288
|
+
const previousRuntime = sessions.get(previousId);
|
|
289
|
+
const previousConversation = terminalConversation;
|
|
290
|
+
sessionId = id;
|
|
291
|
+
terminalConversation = undefined;
|
|
292
|
+
({ app, config, orchestrator } = runtime);
|
|
293
|
+
({ harness, root, agents } = app);
|
|
294
|
+
try {
|
|
295
|
+
await startWeb();
|
|
296
|
+
sessionCatalog.select(id);
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
sessionId = previousId;
|
|
300
|
+
({ app, config, orchestrator } = previousRuntime);
|
|
301
|
+
({ harness, root, agents } = app);
|
|
302
|
+
terminalConversation = previousConversation;
|
|
303
|
+
if (!closing)
|
|
304
|
+
await startWeb().catch((rollbackError) => log(c.red(`恢复网页绑定失败:${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`)));
|
|
305
|
+
if (wasTui && !closing)
|
|
306
|
+
await startTui();
|
|
307
|
+
else if (!closing)
|
|
308
|
+
stopFollowing = await follow(root, context, { replay: true });
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
if (closing)
|
|
312
|
+
return;
|
|
313
|
+
if (wasTui)
|
|
314
|
+
await startTui();
|
|
315
|
+
else {
|
|
316
|
+
stopFollowing = await follow(root, context, { replay: true });
|
|
317
|
+
await printBanner();
|
|
318
|
+
}
|
|
319
|
+
if (closing)
|
|
320
|
+
return;
|
|
321
|
+
harness.resume();
|
|
322
|
+
log(`已切换到 ${sessionId}。其他已打开会话继续运行;网页显示当前会话。`);
|
|
323
|
+
}
|
|
324
|
+
finally {
|
|
325
|
+
switchingSession = false;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
async function printBanner() {
|
|
329
|
+
const controller = await root.agent(context);
|
|
330
|
+
log(c.green("Lemma · 引理 · 多 Agent 协作(Pi Durable)"));
|
|
331
|
+
log(c.dim(`总调度模型:${orchestrator.info?.type ?? config.orchestrator.type} · ${controller.model ? `${controller.model.provider}/${controller.model.modelId}` : orchestrator.describe}`));
|
|
332
|
+
log(c.cyan(`会话:${sessionId} · ${sessionCatalog.get(sessionId).title}(/sessions 管理与切换)`));
|
|
333
|
+
log(c.cyan(`当前输入 → 总控对话 ${root.id};成员各用独立 session_id(/conversation 查看隔离边界)`));
|
|
334
|
+
log(c.dim(`工作目录:${config.workdir}`));
|
|
335
|
+
log(c.dim(`会话存储:${config.storage}`));
|
|
336
|
+
log(c.dim("/setup 配置总控 · /agent add 添加成员 · /agents 查看成员 · /help 操作帮助"));
|
|
337
|
+
if (admin)
|
|
338
|
+
log(`${c.dim("后台网页:")}${c.cyan(admin.url)}`);
|
|
339
|
+
for (const a of agents) {
|
|
340
|
+
log(` ${a.available ? c.green("●") : c.red("○")} ${a.label ?? a.kind}${a.label && a.label !== a.kind ? ` (${a.kind})` : ""} · ${a.transport ?? (config.agents[a.kind].api ? "api" : "cli")}${a.available ? "" : c.dim(` — ${a.reason}`)}`);
|
|
341
|
+
}
|
|
342
|
+
const authWarn = orchestratorKeyWarning(config.orchestrator);
|
|
343
|
+
if (authWarn)
|
|
344
|
+
log(c.yellow(`⚠ ${authWarn}`));
|
|
345
|
+
}
|
|
346
|
+
async function shutdown(code = 0) {
|
|
347
|
+
if (closing)
|
|
348
|
+
return;
|
|
349
|
+
closing = true;
|
|
350
|
+
process.exitCode = code;
|
|
351
|
+
// 即使切换会话时某个资源已关闭或关闭失败,也必须最终退出并释放其余运行时。
|
|
352
|
+
setTimeout(() => process.exit(code), 4000).unref();
|
|
353
|
+
for (const runtime of sessions.values())
|
|
354
|
+
runtime.app.jobs.closing = true;
|
|
355
|
+
stopTerminalStatus();
|
|
356
|
+
terminalUI?.stop();
|
|
357
|
+
setOutputSink(undefined);
|
|
358
|
+
// readline 可能正在同步分发同一批粘贴进来的多行,推迟到分发完再关
|
|
359
|
+
setImmediate(() => rl?.close());
|
|
360
|
+
await admin?.close().catch(() => { });
|
|
361
|
+
await stopFollowing().catch(() => { });
|
|
362
|
+
// 关闭时被打断的后台派工不收尾,下次启动续接它的会话接着做
|
|
363
|
+
await Promise.allSettled([...sessions.values()].map((runtime) => runtime.app.harness.close(context)));
|
|
364
|
+
// 不直接 process.exit():Windows 上句柄未关完就退出会触发 libuv 断言。
|
|
365
|
+
// 让事件循环自然结束;万一有残留句柄,2 秒后兜底退出。
|
|
366
|
+
setTimeout(() => process.exit(code), 2000).unref();
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* 提交一条输入。whenBusy:
|
|
370
|
+
* steer 总调度正忙时插进当前这一轮(在这一轮工具做完后、下一次思考前看到);空闲时就是新的一轮
|
|
371
|
+
* followUp 正忙时排队,这一轮结束后作为新的一轮处理
|
|
372
|
+
*/
|
|
373
|
+
/** 模型服务商因内容政策拦截整段请求(换个说法或续跑都没用,只能重置上下文) */
|
|
374
|
+
const CONTEXT_BLOCKED = /violate .*(terms|usage polic)|blocked as it seems|content (policy|filter)|safety (system|filter)|内容(安全|审核|政策)/i;
|
|
375
|
+
async function ask(text, whenBusy = "followUp") {
|
|
376
|
+
if (configuring)
|
|
377
|
+
throw new Error("正在配置,请完成或取消后再发送任务。");
|
|
378
|
+
const target = root;
|
|
379
|
+
const id = sessionId;
|
|
380
|
+
const submission = await target.submit({ type: "input", content: text, whenBusy }, context);
|
|
381
|
+
const settled = await submission.wait(context);
|
|
382
|
+
if (settled.status !== "done" && id === sessionId && (!terminalConversation || String(terminalConversation.id) === String(root.id))) {
|
|
383
|
+
const { reason, detail } = settled;
|
|
384
|
+
log(c.red(`\n[${id}] 本轮没有完成:${reason ?? settled.status}${detail ? ` — ${detail}` : ""}`));
|
|
385
|
+
if (reason === "model_error" && CONTEXT_BLOCKED.test(detail ?? "")) {
|
|
386
|
+
// 服务商的内容检查拦下的是整段上下文:之后每次请求都会带上它,续跑和重发都没用
|
|
387
|
+
log(c.yellow("(这是模型服务商的内容检查拦截,不是 Lemma 的故障。被拦的那条消息还在上下文里,之后每次请求都会被拦。输入 /new 重置上下文就能恢复;对话记录仍保存在存储里。)"));
|
|
388
|
+
}
|
|
389
|
+
else if (reason === "model_error" && /Provider is not configured/i.test(detail ?? "")) {
|
|
390
|
+
const authWarn = orchestratorKeyWarning(config.orchestrator);
|
|
391
|
+
if (authWarn)
|
|
392
|
+
log(c.yellow(`(${authWarn})`));
|
|
393
|
+
}
|
|
394
|
+
else if (reason === "model_error" || reason === "interrupted" || reason === "turn_limit")
|
|
395
|
+
log(c.dim("(输入 /continue 可以在原来的上下文里续跑)"));
|
|
396
|
+
}
|
|
397
|
+
return settled;
|
|
398
|
+
}
|
|
399
|
+
async function liveState() {
|
|
400
|
+
return harness.snapshot(LiveDoc, root.id, context);
|
|
401
|
+
}
|
|
402
|
+
/** 上一轮出错 / 中断后,不重新输入,直接在原来的上下文里续跑 */
|
|
403
|
+
async function continueRun() {
|
|
404
|
+
const target = root, targetHarness = harness;
|
|
405
|
+
const live = await targetHarness.snapshot(LiveDoc, target.id, context);
|
|
406
|
+
if (live?.run)
|
|
407
|
+
return log(c.dim("总调度正在运行,不需要续跑。"));
|
|
408
|
+
if (!live?.runFailure)
|
|
409
|
+
return log(c.dim("上一轮已经正常结束,没有可以续跑的。"));
|
|
410
|
+
if (live.runFailure.reason === "aborted" || live.runFailure.reason === "reset") {
|
|
411
|
+
log(c.dim(`上一轮是被${live.runFailure.reason === "aborted" ? "中止" : "重置"}的,仍然尝试续跑。`));
|
|
412
|
+
}
|
|
413
|
+
log(c.yellow("续跑上一轮…"));
|
|
414
|
+
const submission = await target.submit({ type: "continue" }, context);
|
|
415
|
+
const settled = await submission.wait(context);
|
|
416
|
+
if (settled.status !== "done") {
|
|
417
|
+
const { reason, detail } = settled;
|
|
418
|
+
log(c.red(reason === "nothing_to_answer" ? "没有需要续跑的内容:上一轮停在已经回答完的地方。" : `续跑没有完成:${reason ?? settled.status}${detail ? ` — ${detail}` : ""}`));
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/** 手动压缩:把较早的对话总结成摘要,总调度之后只看摘要 + 最近的内容(原始记录仍在存储里) */
|
|
422
|
+
async function compactNow(instructions) {
|
|
423
|
+
const target = root, targetHarness = harness;
|
|
424
|
+
log(c.yellow("正在压缩上下文…"));
|
|
425
|
+
const taskId = await target.compact(instructions, context);
|
|
426
|
+
const outcome = (await targetHarness.waitForTask(taskId, context)).state?.outcome;
|
|
427
|
+
if (outcome?.status === "completed") {
|
|
428
|
+
// entryId:空闲时摘要已直接放入;submissionId:正忙,摘要在这一轮的下一个间隙放入;都没有:对话还短,不需要压缩
|
|
429
|
+
const r = outcome.result ?? {};
|
|
430
|
+
log(r.entryId !== undefined
|
|
431
|
+
? c.green("已压缩:较早的对话换成了摘要(原始记录仍在存储里)。")
|
|
432
|
+
: r.submissionId !== undefined
|
|
433
|
+
? c.green("摘要已生成,会在这一轮的下一个间隙放入。")
|
|
434
|
+
: c.dim("对话还不长,没有需要压缩的内容。"));
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
log(c.red(`压缩没有完成:${outcome?.status ?? "未知"}${outcome?.error ? ` — ${outcome.error}` : ""}`));
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const JOB_STATUS = { running: "进行中", done: "完成", failed: "失败", cancelled: "已取消" };
|
|
441
|
+
async function jobList(targetHarness = harness) {
|
|
442
|
+
const doc = (await targetHarness.snapshot(Jobs, context));
|
|
443
|
+
return Object.values(doc?.jobs ?? {}).sort((a, b) => b.startedAt - a.startedAt);
|
|
444
|
+
}
|
|
445
|
+
function jobLine(j) {
|
|
446
|
+
const color = j.status === "running" ? c.cyan : j.status === "done" ? c.green : j.status === "failed" ? c.red : c.dim;
|
|
447
|
+
const seconds = Math.round(((j.endedAt ?? Date.now()) - j.startedAt) / 1000);
|
|
448
|
+
return ` ${color(`${j.id} ${JOB_STATUS[j.status]}`.padEnd(9))} ${j.agent}${j.model ? c.dim(`/${j.model}`) : ""}${j.taskId ? ` · ${j.taskId}` : ""} ${c.dim(`${seconds}s${j.costUsd !== undefined ? ` · $${j.costUsd.toFixed(3)}` : ""}${j.changeId ? ` · 改动 #${j.changeId}` : ""}`)} ${c.dim(clip(j.task, 50))}`;
|
|
449
|
+
}
|
|
450
|
+
async function jobsCommand(arg) {
|
|
451
|
+
const targetApp = app, targetHarness = harness;
|
|
452
|
+
const [sub, target = ""] = arg.split(/\s+/, 2);
|
|
453
|
+
const jobs = await jobList(targetHarness);
|
|
454
|
+
if (sub === "cancel") {
|
|
455
|
+
const ids = target === "all" ? jobs.filter((j) => j.status === "running").map((j) => j.id) : [target];
|
|
456
|
+
if (!ids[0])
|
|
457
|
+
return log(c.dim(target === "all" ? "没有进行中的后台派工。" : "用法:/jobs cancel <编号|all>"));
|
|
458
|
+
for (const id of ids) {
|
|
459
|
+
const r = await targetApp.jobs.cancel(id, "user", context);
|
|
460
|
+
log(r === "cancelled" ? c.yellow(`已取消 ${id}(总调度会收到通知)`) : r === "not_running" ? c.dim(`${id} 已经结束了`) : c.red(`没有后台派工 ${id}`));
|
|
461
|
+
}
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (sub) {
|
|
465
|
+
const j = jobs.find((x) => x.id.toLowerCase() === sub.toLowerCase());
|
|
466
|
+
if (!j)
|
|
467
|
+
return log(c.red(`没有后台派工 ${sub}`));
|
|
468
|
+
log(jobLine(j));
|
|
469
|
+
log(c.dim(` 任务:${j.task}`));
|
|
470
|
+
if (j.sessionId)
|
|
471
|
+
log(c.dim(` 会话:${j.sessionId}`));
|
|
472
|
+
const lines = targetApp.jobs.recent(j.id).slice(-12);
|
|
473
|
+
if (lines.length)
|
|
474
|
+
log([c.dim(" 最近输出:"), ...lines.map((l) => c.dim(` ${l}`))].join("\n"));
|
|
475
|
+
if (j.result)
|
|
476
|
+
log(` 结果:${clip(j.result, 600)}`);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (!jobs.length)
|
|
480
|
+
return log(c.dim("还没有后台派工。总调度派耗时长、互不依赖的任务时会放到后台(background: true)。"));
|
|
481
|
+
const running = jobs.filter((j) => j.status === "running");
|
|
482
|
+
for (const j of [...running, ...jobs.filter((j) => j.status !== "running").slice(0, 10)])
|
|
483
|
+
log(jobLine(j));
|
|
484
|
+
log(c.dim(` /jobs <编号> 看详情和实时输出,/jobs cancel <编号|all> 取消${admin ? `;拓扑:${admin.url}/#/topology` : ""}`));
|
|
485
|
+
}
|
|
486
|
+
/** 单次提问模式:等后台派工和它们触发的后续处理都结束 */
|
|
487
|
+
async function untilSettled() {
|
|
488
|
+
for (;;) {
|
|
489
|
+
const running = (await jobList()).some((j) => j.status === "running");
|
|
490
|
+
const busy = (await liveState())?.run !== undefined;
|
|
491
|
+
if (!running && !busy)
|
|
492
|
+
return;
|
|
493
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const STATUS_TEXT = {
|
|
497
|
+
running: "进行中",
|
|
498
|
+
pending: "待合并",
|
|
499
|
+
empty: "无改动",
|
|
500
|
+
applied: "已合并",
|
|
501
|
+
dropped: "已丢弃",
|
|
502
|
+
conflict: "有冲突",
|
|
503
|
+
};
|
|
504
|
+
function printChanges(all) {
|
|
505
|
+
const list = app.changes.list().filter((c) => all || c.status === "pending" || c.status === "conflict" || c.status === "running");
|
|
506
|
+
if (!list.length) {
|
|
507
|
+
log(c.dim(all ? "还没有隔离派工的改动。" : "没有待合并的改动(/changes all 查看全部)。"));
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
for (const ch of list) {
|
|
511
|
+
const color = ch.status === "pending" ? c.yellow : ch.status === "conflict" ? c.red : ch.status === "applied" ? c.green : c.dim;
|
|
512
|
+
log(` ${color(`#${ch.id}`)} ${color(STATUS_TEXT[ch.status] ?? ch.status)} ${ch.agent}${ch.model ? c.dim(`/${ch.model}`) : ""} ${ch.files.length} 个文件 ${c.green(`+${ch.add}`)} ${c.red(`−${ch.del}`)} ${c.dim(ch.task.replace(/\s+/g, " ").slice(0, 50))}`);
|
|
513
|
+
if (ch.integration)
|
|
514
|
+
log(c.dim(` 集成 ${ch.integration.status} · 来源 ${ch.integration.sources.map((source) => `#${source.id}`).join(" + ")} · 检查 ${ch.integration.reports.filter((report) => report.passed).length}/${ch.integration.checks.length} · /integrate show ${ch.id}`));
|
|
515
|
+
}
|
|
516
|
+
log(c.dim(" /diff <编号> 看改了哪些文件,/apply <编号> 合并到主目录,/drop <编号> 丢弃,/clean 清理已合并的 worktree"));
|
|
517
|
+
}
|
|
518
|
+
async function changeCommand(line) {
|
|
519
|
+
if (/^\/integrate(?:\s|$)/.test(line)) {
|
|
520
|
+
const [, action = "list", ...args] = line.trim().split(/\s+/);
|
|
521
|
+
if (action === "list" || action === "show") {
|
|
522
|
+
const records = Object.values((await harness.snapshot(Integrations, context))?.records ?? {}).filter((record) => record.integration?.controllerId === String((terminalConversation ?? root).id) && (action !== "show" || record.id === args[0]));
|
|
523
|
+
if (!records.length)
|
|
524
|
+
log("当前没有集成记录;/integrate create <改动ID1> <改动ID2> 启动联合合并与检查。");
|
|
525
|
+
for (const record of records)
|
|
526
|
+
log(JSON.stringify(integrationSummary(app.changes.get(record.id) ?? record), null, 2));
|
|
527
|
+
return true;
|
|
528
|
+
}
|
|
529
|
+
if (terminalConversation && String(terminalConversation.id) !== String(root.id))
|
|
530
|
+
throw new Error("请先 /main 返回总控操作集成。");
|
|
531
|
+
if (action === "cancel" && args.length === 1) {
|
|
532
|
+
await app.cancelIntegration(root.id, args[0], context);
|
|
533
|
+
log(`集成 ${args[0]} 已取消;现场与来源分支保留。`);
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
if (action === "rerun" && args.length === 1) {
|
|
537
|
+
const record = await app.rerunIntegration(root.id, args[0], context);
|
|
538
|
+
log(JSON.stringify(integrationSummary(record), null, 2));
|
|
539
|
+
return true;
|
|
540
|
+
}
|
|
541
|
+
if (action === "repair" && args.length >= 2) {
|
|
542
|
+
const [targetId, member, ...noteParts] = args;
|
|
543
|
+
const record = await app.repairIntegration(root.id, targetId, member, noteParts.join(" ").trim() || undefined, context);
|
|
544
|
+
log(JSON.stringify(integrationSummary(record), null, 2));
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
if (action !== "create" || args.length < 2)
|
|
548
|
+
throw new Error("/integrate create <改动ID1> <改动ID2> … · /integrate rerun <ID> · /integrate repair <ID> <成员ID> [说明] · /integrate list · /integrate show <ID> · /integrate cancel <ID>");
|
|
549
|
+
const record = await app.integrate(root.id, args, context);
|
|
550
|
+
log(JSON.stringify(integrationSummary(record), null, 2));
|
|
551
|
+
return true;
|
|
552
|
+
}
|
|
553
|
+
const targetChanges = app.changes;
|
|
554
|
+
const [cmd, arg = ""] = line.split(/\s+/, 2);
|
|
555
|
+
switch (cmd) {
|
|
556
|
+
case "/changes":
|
|
557
|
+
printChanges(arg === "all");
|
|
558
|
+
return true;
|
|
559
|
+
case "/diff": {
|
|
560
|
+
const ch = app.changes.get(arg);
|
|
561
|
+
if (!ch) {
|
|
562
|
+
log(c.red(`找不到改动 ${arg || "(请给出编号)"}`));
|
|
563
|
+
return true;
|
|
564
|
+
}
|
|
565
|
+
log(`#${ch.id} ${ch.branch} ${STATUS_TEXT[ch.status] ?? ch.status}${ch.basedOn ? c.dim(` 基于 #${ch.basedOn}`) : ""}`);
|
|
566
|
+
if (ch.integration)
|
|
567
|
+
log(c.dim(`联合检查:${ch.integration.status};/integrate show ${ch.id} 查看完整记录。`));
|
|
568
|
+
for (const f of ch.files)
|
|
569
|
+
log(` ${c.green(`+${f.add}`.padStart(6))} ${c.red(`−${f.del}`.padEnd(6))} ${f.path}`);
|
|
570
|
+
if (admin)
|
|
571
|
+
log(c.dim(` 完整差异:${admin.url}/#/changes/${ch.id}`));
|
|
572
|
+
return true;
|
|
573
|
+
}
|
|
574
|
+
case "/apply":
|
|
575
|
+
case "/drop": {
|
|
576
|
+
let pick = arg;
|
|
577
|
+
if (!pick) {
|
|
578
|
+
const pending = pendingChanges(targetChanges);
|
|
579
|
+
if (!pending.length) {
|
|
580
|
+
log(c.dim("没有待合并的改动。"));
|
|
581
|
+
return true;
|
|
582
|
+
}
|
|
583
|
+
if (terminalUI) {
|
|
584
|
+
pick = (await terminalUI.selectPendingChange(cmd, pending.map((ch) => ({
|
|
585
|
+
id: ch.id, agent: ch.agent, branch: ch.branch, root: ch.root,
|
|
586
|
+
filesCount: ch.files.length, add: ch.add, del: ch.del, task: ch.task, isIntegration: !!ch.integration,
|
|
587
|
+
})))) ?? "";
|
|
588
|
+
if (!pick) {
|
|
589
|
+
log(c.dim("已取消。"));
|
|
590
|
+
return true;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
else {
|
|
594
|
+
log(c.red(`用法:${cmd} <编号>(或 ${cmd} all 处理全部待合并的改动)`));
|
|
595
|
+
return true;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const ids = pick === "all" ? pendingChanges(targetChanges).map((ch) => ch.id) : [pick];
|
|
599
|
+
if (!ids.length)
|
|
600
|
+
log(c.dim("没有待合并的改动。"));
|
|
601
|
+
for (const id of ids) {
|
|
602
|
+
const r = cmd === "/apply" ? await applyChange(targetChanges, id) : await dropChange(targetChanges, id);
|
|
603
|
+
log(r.ok ? c.green(r.message) : c.red(r.message));
|
|
604
|
+
}
|
|
605
|
+
return true;
|
|
606
|
+
}
|
|
607
|
+
case "/clean": {
|
|
608
|
+
const r = await cleanChanges(targetChanges);
|
|
609
|
+
log(c.green(r.message));
|
|
610
|
+
return true;
|
|
611
|
+
}
|
|
612
|
+
default:
|
|
613
|
+
return false;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
async function command(line) {
|
|
617
|
+
if (/^\/fast(?:\s|$)/.test(line)) {
|
|
618
|
+
const rest = line.slice(5).trim();
|
|
619
|
+
if (!rest) {
|
|
620
|
+
log(c.dim("用法:/fast [成员ID|readonly] <单文件任务说明>(跳过总调度首尾往返,直通首选编码成员;改动≤2文件时直接弹出合并确认,超出自动升级保留分支)"));
|
|
621
|
+
return true;
|
|
622
|
+
}
|
|
623
|
+
if (terminalConversation && String(terminalConversation.id) !== String(root.id))
|
|
624
|
+
throw new Error("请先 /main 返回总控再使用 /fast。");
|
|
625
|
+
const firstSpace = rest.search(/\s/);
|
|
626
|
+
const firstToken = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
|
|
627
|
+
const afterFirst = firstSpace === -1 ? "" : rest.slice(firstSpace).trim();
|
|
628
|
+
let member;
|
|
629
|
+
let readonly = false;
|
|
630
|
+
let taskText = rest;
|
|
631
|
+
if (firstToken === "readonly" && afterFirst) {
|
|
632
|
+
readonly = true;
|
|
633
|
+
taskText = afterFirst;
|
|
634
|
+
}
|
|
635
|
+
else if (afterFirst && Object.prototype.hasOwnProperty.call(config.agents, firstToken)) {
|
|
636
|
+
member = firstToken;
|
|
637
|
+
taskText = afterFirst;
|
|
638
|
+
}
|
|
639
|
+
log(c.dim(`⚡ 单跳快路启动${readonly ? "(只读免隔离)" : ""}${member ? ` · 成员 ${member}` : ""}…`));
|
|
640
|
+
const outcome = await app.fastDispatch(root.id, taskText, {
|
|
641
|
+
member,
|
|
642
|
+
readonly,
|
|
643
|
+
onOutput: (chunk) => {
|
|
644
|
+
for (const ln of chunk.split(/\r?\n/))
|
|
645
|
+
if (ln.trim())
|
|
646
|
+
log(c.dim(` ${ln}`));
|
|
647
|
+
},
|
|
648
|
+
});
|
|
649
|
+
log(outcome.result.isError ? c.red(outcome.result.text) : outcome.result.text);
|
|
650
|
+
if (outcome.applyMessage)
|
|
651
|
+
log(outcome.applied ? c.green(`✓ ${outcome.applyMessage}`) : c.yellow(outcome.applyMessage));
|
|
652
|
+
else if (outcome.escalated && outcome.changeId)
|
|
653
|
+
log(c.yellow(`⚠ 快路改动已自动升级保留在独立分支 #${outcome.changeId},建议 /diff ${outcome.changeId} 审查后再 /apply。`));
|
|
654
|
+
return true;
|
|
655
|
+
}
|
|
656
|
+
if (/^\/workflow(?:\s|$)/.test(line)) {
|
|
657
|
+
const [, action = "status", extra] = line.split(/\s+/);
|
|
658
|
+
if (extra || !["status", "pause", "resume"].includes(action))
|
|
659
|
+
throw new Error("/workflow status|pause|resume");
|
|
660
|
+
if (action !== "status" && terminalConversation && String(terminalConversation.id) !== String(root.id))
|
|
661
|
+
throw new Error("请先 /main 返回总控控制协作流程。");
|
|
662
|
+
const state = await app.workflow(action, context);
|
|
663
|
+
log(state.paused ? "自动协作已暂停;现有派工继续收尾,不启动后续派工。/workflow resume 恢复。" : "自动协作已启用;仅推进显式授权的任务。/ready 查看,/workflow pause 暂停。");
|
|
664
|
+
return true;
|
|
665
|
+
}
|
|
666
|
+
if (line === "/ready") {
|
|
667
|
+
const board = await harness.snapshot(Board, context);
|
|
668
|
+
const queue = board ? readyTasks(board, String((terminalConversation ?? root).id)).filter((state) => board.tasks[state.id].status === "todo") : [];
|
|
669
|
+
if (!queue.length)
|
|
670
|
+
log("当前没有待派发任务;/tasks 查看执行、复核和受阻记录。");
|
|
671
|
+
for (const state of queue) {
|
|
672
|
+
log(`${state.id} · ${state.ready ? "就绪" : state.reasons.join(";")} · ${board.tasks[state.id].automation ? "已授权自动派发" : "等待总控派发"}`);
|
|
673
|
+
}
|
|
674
|
+
return true;
|
|
675
|
+
}
|
|
676
|
+
if (line === "/history") {
|
|
677
|
+
if (terminalUI)
|
|
678
|
+
await terminalUI.loadEarlier();
|
|
679
|
+
else
|
|
680
|
+
log("请通过 npm start 打开终端,使用滚轮或 PgUp 翻阅历史。");
|
|
681
|
+
return true;
|
|
682
|
+
}
|
|
683
|
+
if (line === "/thinking") {
|
|
684
|
+
if (terminalUI)
|
|
685
|
+
terminalUI.toggleThinking();
|
|
686
|
+
else
|
|
687
|
+
log("请通过 npm start 打开终端,使用 /thinking 或 Alt+T 切换思考记录。");
|
|
688
|
+
return true;
|
|
689
|
+
}
|
|
690
|
+
if (await taskCommand(line, { app, config, context, log, async assertIdle() {
|
|
691
|
+
if (configuring || switchingSession || closing)
|
|
692
|
+
throw new Error("当前正在配置、切换或退出。");
|
|
693
|
+
if ((await harness.snapshot(LiveDoc, root.id, context))?.run)
|
|
694
|
+
throw new Error("总控正在运行,请先等待或 /abort 再恢复任务。");
|
|
695
|
+
} }))
|
|
696
|
+
return true;
|
|
697
|
+
if (line === "/progress") {
|
|
698
|
+
const state = resourceSnapshot(await harness.snapshot(Resources, context));
|
|
699
|
+
log(`运行 ${state.running.length} · 排队 ${state.queued.length} · 预留 $${state.reservedUsd.toFixed(4)}(估计)`);
|
|
700
|
+
for (const claim of state.queued)
|
|
701
|
+
log(`${claim.id} · ${claim.member} · ${claim.reason}`);
|
|
702
|
+
log("/tasks 查看依赖、验收和结果;/operations 查看待核对外部操作。");
|
|
703
|
+
return true;
|
|
704
|
+
}
|
|
705
|
+
if (/^\/operations(?:\s|$)/.test(line)) {
|
|
706
|
+
const [, action, id, outcome, ...parts] = line.trim().split(/\s+/);
|
|
707
|
+
if (!action || action === "list") {
|
|
708
|
+
for (const item of operationList(await harness.snapshot(Operations, context)))
|
|
709
|
+
log(`${item.id} · ${item.member}/${item.tool} · ${item.status} · ${item.result?.failure?.kind ?? ""}${item.result?.failure ? ` · ${item.result.failure.message}` : ""}${item.result?.failure?.retryAt ? ` · 重试时间 ${new Date(item.result.failure.retryAt).toISOString()}` : ""}${item.resolution ? ` · 核对 ${item.resolution.outcome}:${item.resolution.evidence}` : ""}`);
|
|
710
|
+
log("核对远端后:/operations resolve <ID> succeeded|not_applied <依据>;此命令只记录核对结论,不执行外部操作。");
|
|
711
|
+
return true;
|
|
712
|
+
}
|
|
713
|
+
if (action !== "resolve" || !id || !["succeeded", "not_applied"].includes(outcome ?? "") || !parts.length)
|
|
714
|
+
throw new Error("用法:/operations resolve <ID> succeeded|not_applied <人工核对依据>");
|
|
715
|
+
await assertConfigIdle();
|
|
716
|
+
log(await harness.commit((tx) => resolveOperation(tx, id, outcome, parts.join(" "), Date.now()), context));
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
if (line === "/help") {
|
|
720
|
+
log(MEMBER_HELP);
|
|
721
|
+
log(TASK_HELP);
|
|
722
|
+
log("/fast [成员ID|readonly] <任务> 单跳快路直连 · /sessions 管理会话 · /tasks 分工 · /jobs 后台任务 · /model 选择当前总控模型 · /web 网页 · /exit 退出");
|
|
723
|
+
log("/ready 就绪队列 · /workflow status|pause|resume 协作控制 · Enter 发送 · Ctrl+J 换行 · 滚轮/PgUp/PgDn 翻阅 · Ctrl+Home/End 到顶/最新 · Alt+End 最新 · Ctrl+K 会话 · Alt+C 关系树 · Ctrl+L 模型 · Ctrl+T 任务面板 · Ctrl+E 工具详情 · Alt+T 思考");
|
|
724
|
+
log("/history 补载更早记录 · /thinking 展开/收起思考 · Ctrl+Shift+F 搜索已加载记录;思考仅展示服务实际返回的内容。");
|
|
725
|
+
return true;
|
|
726
|
+
}
|
|
727
|
+
if (/^\/(?:agent|setup|tool|limits|mcp)(?:\s|$)/.test(line)) {
|
|
728
|
+
if (configuring)
|
|
729
|
+
throw new Error("配置正在进行中。");
|
|
730
|
+
configuring = true;
|
|
731
|
+
try {
|
|
732
|
+
return await memberSettingsCommand(line, { path: configPath, config: () => config, question: settingQuestion, assertIdle: assertConfigIdle, commit: commitSettings, log });
|
|
733
|
+
}
|
|
734
|
+
finally {
|
|
735
|
+
configuring = false;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (/^\/sessions?(?:\s|$)/.test(line)) {
|
|
739
|
+
await sessionCommand(line);
|
|
740
|
+
return true;
|
|
741
|
+
}
|
|
742
|
+
if (line === "/conversations") {
|
|
743
|
+
await showTerminalConversations();
|
|
744
|
+
return true;
|
|
745
|
+
}
|
|
746
|
+
if (line === "/tree") {
|
|
747
|
+
await showTerminalConversations(true);
|
|
748
|
+
return true;
|
|
749
|
+
}
|
|
750
|
+
if (line === "/model" || line.startsWith("/model ")) {
|
|
751
|
+
await modelCommand(line.slice(6).trim());
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
if (line === "/main") {
|
|
755
|
+
await selectTerminalConversation(String(root.id));
|
|
756
|
+
return true;
|
|
757
|
+
}
|
|
758
|
+
if (line === "/taskgraph") {
|
|
759
|
+
if (terminalUI)
|
|
760
|
+
terminalUI.toggleTasks();
|
|
761
|
+
else {
|
|
762
|
+
const graph = await harness.watchTaskGraph(context);
|
|
763
|
+
try {
|
|
764
|
+
const tasks = Object.values(graph.value.tasks);
|
|
765
|
+
if (!tasks.length)
|
|
766
|
+
log("当前没有活动的原生任务。");
|
|
767
|
+
for (const task of tasks)
|
|
768
|
+
log(`${task.id} · ${task.kind} · ${task.state.status} · 对话 ${task.conversationId}${task.owner ? ` · 父任务 ${task.owner}` : ""}`);
|
|
769
|
+
}
|
|
770
|
+
finally {
|
|
771
|
+
await graph.stop();
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
if (line === "/conversation" || line === "/id") {
|
|
777
|
+
log(`会话编号:${sessionId}(可读名称,不是模型对话 ID)`);
|
|
778
|
+
log(`总控 conversation_id:${root.id}(Pi Durable ID,仅在本会话存储内唯一)`);
|
|
779
|
+
log(`会话存储:${config.storage}`);
|
|
780
|
+
log(terminalConversation && String(terminalConversation.id) !== String(root.id)
|
|
781
|
+
? `当前只读查看子对话 CID:${terminalConversation.id},消息不会发送。/main 返回总控;成员历史仍由其原任务管理。`
|
|
782
|
+
: "当前输入发送给总控;成员分别持有自己的上下文,仅接收派工说明、项目背景与显式交接内容。总控只收到派工结果,不自动复制成员完整聊天记录。");
|
|
783
|
+
log("重启默认恢复上次选中的会话;--session=编号 可指定恢复。Ctrl+N / /session new 新建独立聊天;/new 只重置当前总控上下文,保留任务与成员登记。");
|
|
784
|
+
return true;
|
|
785
|
+
}
|
|
786
|
+
if (line === "/members") {
|
|
787
|
+
const records = (await harness.snapshot(AgentSessions, context))?.sessions ?? {};
|
|
788
|
+
log(`所属会话:${sessionId} · 总控 conversation_id=${root.id};成员 ID 只可在所属会话续接。`);
|
|
789
|
+
for (const [id, record] of Object.entries(records))
|
|
790
|
+
log(`${config.agents[record.agent]?.name ?? record.agent} · session_id=${id} · 总控=${record.controllerId ?? String(root.id)} · ${record.model ?? "默认模型"} · ${record.rounds ?? 0} 轮 · ${record.lastTask ?? ""}`);
|
|
791
|
+
if (!Object.keys(records).length)
|
|
792
|
+
log("当前会话还没有成员上下文;任务派工后会显示在这里。");
|
|
793
|
+
return true;
|
|
794
|
+
}
|
|
795
|
+
if (/^\/result(?:\s|$)/.test(line)) {
|
|
796
|
+
const [, id, selection = "0", fieldOffset, extra] = line.trim().split(/\s+/);
|
|
797
|
+
const field = /^\d+$/.test(selection) ? undefined : selection;
|
|
798
|
+
if (!id || extra || (fieldOffset !== undefined && (!field || !/^\d+$/.test(fieldOffset))))
|
|
799
|
+
throw new Error("用法:/result <result_id> [字符偏移或结构化字段] [字段内字符偏移]");
|
|
800
|
+
const report = (await harness.snapshot(Results, root.id, id, context))?.result;
|
|
801
|
+
if (!report)
|
|
802
|
+
throw new Error("当前总控没有这个结果。");
|
|
803
|
+
const page = !field ? resultPage(report, Number(selection), 4000) : { ...resultExcerpt(report, { field, offset: Number(fieldOffset ?? 0), limit: 8000 }), id: report.id, member: report.member, status: report.status };
|
|
804
|
+
log(`${page.id} · ${page.member} · ${page.status} · ${page.offset}/${page.totalChars}\n${page.text}`);
|
|
805
|
+
if (page.nextOffset !== null)
|
|
806
|
+
log(`下一页:/result ${id} ${field ? `${field} ` : ""}${page.nextOffset}`);
|
|
807
|
+
return true;
|
|
808
|
+
}
|
|
809
|
+
if (line === "/learn" || line === "/repair") {
|
|
810
|
+
const learning = await harness.snapshot(Learning, context);
|
|
811
|
+
log(`自动验收与修复:${config.autonomy.enabled ? "开启" : "关闭"} · 最多 ${config.autonomy.maxRepairAttempts} 次 · 检查 ${config.autonomy.checks.map((c) => c.name).join("、") || "未配置"}`);
|
|
812
|
+
for (const event of learning?.events.slice(-8) ?? [])
|
|
813
|
+
log(`${event.agent} 修复 ${event.attempt} · ${event.status} · ${event.task}`);
|
|
814
|
+
for (const lesson of learning?.lessons.slice(-5) ?? [])
|
|
815
|
+
log(`已验证记录:${lesson.task} · ${lesson.checks.join("、")} · ${lesson.repairs} 次修复 · 改动 ${lesson.changeId ?? "未知"}${lesson.resolution ? `\n ${lesson.resolution.slice(0, 200)}` : ""}`);
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
if (await changeCommand(line))
|
|
819
|
+
return true;
|
|
820
|
+
const [head, ...rest] = line.split(/\s+/);
|
|
821
|
+
const arg = rest.join(" ").trim();
|
|
822
|
+
if (head === "/queue") {
|
|
823
|
+
if (!arg) {
|
|
824
|
+
log(c.red("用法:/queue <任务>(排到当前这一轮之后)"));
|
|
825
|
+
return true;
|
|
826
|
+
}
|
|
827
|
+
log(c.dim("已提交:当前会话忙时排到下一轮,空闲时直接开始。"));
|
|
828
|
+
void ask(arg, "followUp").catch((error) => log(c.red(`出错:${error instanceof Error ? error.message : String(error)}`)));
|
|
829
|
+
return true;
|
|
830
|
+
}
|
|
831
|
+
if (head === "/goal") {
|
|
832
|
+
const goal = app.project.goal();
|
|
833
|
+
if (!goal)
|
|
834
|
+
log(c.dim(`还没有项目目标。可以自己写 ${app.project.goalPath},或者把项目目标告诉总调度,让它起草(会标明待你确认)。`));
|
|
835
|
+
else
|
|
836
|
+
log(`${c.dim(app.project.goalPath)}\n${goal}`);
|
|
837
|
+
return true;
|
|
838
|
+
}
|
|
839
|
+
if (head === "/tasks") {
|
|
840
|
+
const board = (await harness.snapshot(Board, context));
|
|
841
|
+
const tasks = boardTasks(board);
|
|
842
|
+
if (!tasks.length) {
|
|
843
|
+
log(c.dim("还没有分工表。项目级、多步骤的任务,总调度会先拆成任务(plan_tasks)。"));
|
|
844
|
+
return true;
|
|
845
|
+
}
|
|
846
|
+
const color = { done: c.green, doing: c.cyan, review: c.yellow, blocked: c.red, dropped: c.dim, todo: (s) => s };
|
|
847
|
+
for (const t of tasks) {
|
|
848
|
+
const tint = color[t.status] ?? ((s) => s);
|
|
849
|
+
log(` ${tint(`${t.id} ${STATUS_LABEL[t.status]}`.padEnd(8))} ${t.title}${c.dim(`${t.role ? ` ·${t.role}` : ""}${t.owner ? ` ·${t.owner}` : ""}${t.deps.length ? ` ·依赖 ${t.deps.join(",")}` : ""}${t.changes.length ? ` ·改动 ${t.changes.map((x) => `#${x}`).join(",")}` : ""}`)}`);
|
|
850
|
+
if (t.latestResult)
|
|
851
|
+
log(c.dim(` 结果:${t.latestResult} · /result ${t.latestResult}`));
|
|
852
|
+
const state = taskReadiness(board, t);
|
|
853
|
+
if (t.status === "todo")
|
|
854
|
+
log(` ${state.ready ? "就绪" : state.reasons.join(";")} · ${t.automation ? "自动派发已授权" : "等待派发"}`);
|
|
855
|
+
if (t.reviewer) {
|
|
856
|
+
const check = t.checksByMember?.at(-1);
|
|
857
|
+
log(` 独立复核:${t.reviewer.member} · ${check?.status ?? "等待交付"}${check?.evidence ? ` · ${check.evidence.slice(0, 200)}` : ""}`);
|
|
858
|
+
}
|
|
859
|
+
if (t.verification)
|
|
860
|
+
log(` 机器检查:${t.verification.passed ? "通过,仍需复核" : "未通过"} · ${t.verification.checks.map((check) => `${check.name}:${check.passed ? "通过" : "失败"}`).join("、")}`);
|
|
861
|
+
if (t.review)
|
|
862
|
+
log(` 复核:${t.review.verdict} · ${t.review.evidence.slice(0, 250)}`);
|
|
863
|
+
const recovery = t.recoveries?.at(-1);
|
|
864
|
+
if (recovery)
|
|
865
|
+
log(` 恢复:${recovery.action} → ${recovery.member} · ${recovery.status} · ${recovery.note.slice(0, 180)}`);
|
|
866
|
+
if (["todo", "blocked"].includes(t.status) && t.lastAttempt)
|
|
867
|
+
log(c.dim(` /task inspect ${t.id} · /task resume ${t.id} <依据> · /task supply ${t.id} <资料> · /task reassign ${t.id} <成员> <依据>`));
|
|
868
|
+
}
|
|
869
|
+
log(c.dim(` 完整分工表:${app.project.assignPath}${admin ? ` 后台:${admin.url}/#/project` : ""}`));
|
|
870
|
+
return true;
|
|
871
|
+
}
|
|
872
|
+
if (head === "/rules") {
|
|
873
|
+
if (arg === "init") {
|
|
874
|
+
const r = initRules(config.workdir);
|
|
875
|
+
log(r.ok ? c.green(r.message) : c.yellow(r.message));
|
|
876
|
+
return true;
|
|
877
|
+
}
|
|
878
|
+
if (arg === "sync") {
|
|
879
|
+
const r = syncRules(config.workdir);
|
|
880
|
+
if (!r.ok)
|
|
881
|
+
log(c.yellow(r.message));
|
|
882
|
+
else {
|
|
883
|
+
log(c.green(r.message));
|
|
884
|
+
const word = { created: "新建", updated: "更新", unchanged: "未变" };
|
|
885
|
+
for (const x of r.results)
|
|
886
|
+
log(` ${x.action === "unchanged" ? c.dim(word[x.action]) : c.green(word[x.action])} ${x.file}`);
|
|
887
|
+
log(c.dim(" 记得把这些文件提交进 git(还没提交时,新派工的 worktree 也会带上它们)"));
|
|
888
|
+
}
|
|
889
|
+
return true;
|
|
890
|
+
}
|
|
891
|
+
const scan = scanConventions(config.workdir);
|
|
892
|
+
const label = { claude: "Claude", codex: "Codex", gemini: "Gemini" };
|
|
893
|
+
for (const k of ["claude", "codex", "gemini"]) {
|
|
894
|
+
const m = scan.members[k];
|
|
895
|
+
const instr = m.instructions.map((f) => `${f.scope === "user" ? "~/" : ""}${f.rel}${f.size === 0 ? c.dim("(空)") : ""}${f.rules === "synced" ? c.green("✓规则") : f.rules ? c.yellow("✗规则") : ""}`);
|
|
896
|
+
log(` ${c.cyan(label[k].padEnd(7))} 说明:${instr.join("、") || c.red("无")}${c.dim(` 设置 ${m.settings.length} · 技能 ${m.skills} · 命令 ${m.commands} · 子 agent ${m.subagents}`)}`);
|
|
897
|
+
}
|
|
898
|
+
for (const ch of scan.checks) {
|
|
899
|
+
const mark = ch.level === "warn" ? c.yellow("!") : ch.level === "ok" ? c.green("✓") : c.dim("i");
|
|
900
|
+
log(` ${mark} ${ch.title}${ch.detail ? c.dim(` ${ch.detail}`) : ""}`);
|
|
901
|
+
}
|
|
902
|
+
log(c.dim(` /rules init 生成共同规则模板、/rules sync 同步到各家说明文件${admin ? `;完整视图:${admin.url}/#/conventions` : ""}`));
|
|
903
|
+
return true;
|
|
904
|
+
}
|
|
905
|
+
if (head === "/jobs") {
|
|
906
|
+
await jobsCommand(arg);
|
|
907
|
+
return true;
|
|
908
|
+
}
|
|
909
|
+
if (head === "/continue") {
|
|
910
|
+
await continueRun();
|
|
911
|
+
return true;
|
|
912
|
+
}
|
|
913
|
+
if (head === "/compact") {
|
|
914
|
+
await compactNow(arg || undefined);
|
|
915
|
+
return true;
|
|
916
|
+
}
|
|
917
|
+
switch (line) {
|
|
918
|
+
case "/exit":
|
|
919
|
+
case "/quit":
|
|
920
|
+
await shutdown(0);
|
|
921
|
+
return true;
|
|
922
|
+
case "/agents":
|
|
923
|
+
await printBanner();
|
|
924
|
+
log(MEMBER_HELP);
|
|
925
|
+
return true;
|
|
926
|
+
case "/web":
|
|
927
|
+
log(admin ? `后台网页:${c.cyan(admin.url)}` : c.dim("后台网页没有开启(--no-web 或配置 web.enabled=false)"));
|
|
928
|
+
return true;
|
|
929
|
+
case "/usage": {
|
|
930
|
+
const usage = (await harness.usage(context));
|
|
931
|
+
const entries = Object.values((await harness.snapshot(CostLedger, context))?.entries ?? {});
|
|
932
|
+
for (const category of ["member", "repair"]) {
|
|
933
|
+
const items = entries.filter((entry) => entry.category === category);
|
|
934
|
+
log(`${category === "member" ? "成员派工" : "自动返工"}:已知 $${items.reduce((sum, entry) => sum + (entry.costUsd ?? 0), 0).toFixed(4)} · ${items.filter((entry) => entry.costUsd === null).length} 次费用未知`);
|
|
935
|
+
}
|
|
936
|
+
const resources = resourceSnapshot(await harness.snapshot(Resources, context));
|
|
937
|
+
log(`并行预留 $${resources.reservedUsd.toFixed(4)}(不是已花费);总控/子调度用量见模型统计,角色费用尚不可完全分摊。`);
|
|
938
|
+
for (const [name, u] of Object.entries(usage.models ?? {})) {
|
|
939
|
+
log(` ${name}: 输入 ${u.input ?? 0} / 输出 ${u.output ?? 0} tokens`);
|
|
940
|
+
}
|
|
941
|
+
return true;
|
|
942
|
+
}
|
|
943
|
+
case "/abort":
|
|
944
|
+
case "/abort all": {
|
|
945
|
+
const target = root, targetApp = app, targetHarness = harness;
|
|
946
|
+
await target.abort(context);
|
|
947
|
+
log(c.yellow("已中止。"));
|
|
948
|
+
const running = (await jobList(targetHarness)).filter((j) => j.status === "running");
|
|
949
|
+
if (line === "/abort all") {
|
|
950
|
+
for (const j of running)
|
|
951
|
+
await targetApp.jobs.cancel(j.id, "user", context);
|
|
952
|
+
if (running.length)
|
|
953
|
+
log(c.yellow(`后台派工 ${running.map((j) => j.id).join("、")} 也已取消。`));
|
|
954
|
+
}
|
|
955
|
+
else if (running.length) {
|
|
956
|
+
log(c.dim(`后台还有 ${running.length} 个派工在跑(${running.map((j) => j.id).join("、")}),做完后结果会发回总调度。/abort all 连它们一起停。`));
|
|
957
|
+
}
|
|
958
|
+
return true;
|
|
959
|
+
}
|
|
960
|
+
case "/new":
|
|
961
|
+
await root.reset(undefined, context);
|
|
962
|
+
log(c.yellow("已开始新的上下文(历史仍保存在存储里)。"));
|
|
963
|
+
return true;
|
|
964
|
+
default:
|
|
965
|
+
return false;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
async function startRepl() {
|
|
969
|
+
await printBanner();
|
|
970
|
+
log(c.dim("\n输入任务开始协作。/sessions 管理隔离会话;/agents /web /usage /abort /new /exit;运行中 Ctrl+C 中止本轮。"));
|
|
971
|
+
log(c.dim("运行中:直接输入 = 插话(当前这一轮就能看到),/queue <任务> 排到下一轮;/continue 续跑中断的一轮,/compact 压缩上下文"));
|
|
972
|
+
log(c.dim("项目:/goal 最终目标、/tasks 分工表、/rules 各成员的规范文件(/rules init、/rules sync)"));
|
|
973
|
+
log(c.dim("后台:/jobs 后台派工(/jobs <编号>、/jobs cancel <编号|all>),/abort all 连后台派工一起停"));
|
|
974
|
+
log(c.dim("改动:/changes 待合并的改动、/diff <编号>、/apply <编号>、/drop <编号>、/clean\n"));
|
|
975
|
+
if (pendingChanges(app.changes).length) {
|
|
976
|
+
log(c.yellow(`有 ${pendingChanges(app.changes).length} 个改动等你确认合并:`));
|
|
977
|
+
printChanges(false);
|
|
978
|
+
log();
|
|
979
|
+
}
|
|
980
|
+
const terminalOutput = new Writable({ write(chunk, _encoding, callback) { if (!plainQuestion?.secret)
|
|
981
|
+
process.stdout.write(chunk); callback(); } });
|
|
982
|
+
const repl = createInterface({ input: process.stdin, output: terminalOutput, terminal: !!process.stdin.isTTY && !!process.stdout.isTTY, prompt: `${c.cyan("你 ›")} ` });
|
|
983
|
+
rl = repl;
|
|
984
|
+
let busy = 0;
|
|
985
|
+
replIdle = () => busy === 0 && !closing;
|
|
986
|
+
repl.on("SIGINT", async () => {
|
|
987
|
+
if (plainQuestion) {
|
|
988
|
+
const question = plainQuestion;
|
|
989
|
+
plainQuestion = undefined;
|
|
990
|
+
question.reject(new Error("配置已取消,未保存。"));
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
if (busy === 0)
|
|
994
|
+
return shutdown(0);
|
|
995
|
+
log(c.yellow("\n正在中止本轮…"));
|
|
996
|
+
await root.abort(context);
|
|
997
|
+
repl.prompt();
|
|
998
|
+
});
|
|
999
|
+
// 命令按输入顺序一个一个执行(一次粘贴多行时,/apply 之后的 /clean 要等 /apply 做完);
|
|
1000
|
+
// /abort 和 /exit 不排队,随时生效。任务不排在这里:总调度自己有输入队列。
|
|
1001
|
+
let commands = Promise.resolve();
|
|
1002
|
+
const immediate = new Set(["/abort", "/abort all", "/exit", "/quit"]);
|
|
1003
|
+
repl.on("line", async (raw) => {
|
|
1004
|
+
if (plainQuestion) {
|
|
1005
|
+
const question = plainQuestion;
|
|
1006
|
+
plainQuestion = undefined;
|
|
1007
|
+
if (question.secret && "history" in repl)
|
|
1008
|
+
repl.history.splice(0);
|
|
1009
|
+
log();
|
|
1010
|
+
question.resolve(raw);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
const line = raw.trim();
|
|
1014
|
+
if (!line)
|
|
1015
|
+
return repl.prompt();
|
|
1016
|
+
if (line.startsWith("/")) {
|
|
1017
|
+
const run = async () => {
|
|
1018
|
+
try {
|
|
1019
|
+
if (!(await command(line)))
|
|
1020
|
+
log(c.red(`未知命令:${line}`));
|
|
1021
|
+
}
|
|
1022
|
+
catch (error) {
|
|
1023
|
+
log(c.red(`出错:${error instanceof Error ? error.message : String(error)}`));
|
|
1024
|
+
}
|
|
1025
|
+
if (!closing)
|
|
1026
|
+
repl.prompt();
|
|
1027
|
+
};
|
|
1028
|
+
if (immediate.has(line))
|
|
1029
|
+
await run();
|
|
1030
|
+
else
|
|
1031
|
+
commands = commands.then(run);
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
// 总调度正在干活:这句话插进当前这一轮(steer),它在这一轮工具做完后就能看到;
|
|
1035
|
+
// 想排到下一轮用 /queue。插话和原来那一轮一起结束,提示符由原来那一轮负责打印。
|
|
1036
|
+
// 先同步占位,避免多行粘贴时两个 line 事件同时通过下面的“是否正在运行”检查。
|
|
1037
|
+
busy++;
|
|
1038
|
+
let running = false;
|
|
1039
|
+
try {
|
|
1040
|
+
running = (await liveState())?.run !== undefined;
|
|
1041
|
+
}
|
|
1042
|
+
finally {
|
|
1043
|
+
busy--;
|
|
1044
|
+
}
|
|
1045
|
+
if (running) {
|
|
1046
|
+
log(c.dim("↪ 已插入当前这一轮,总调度在下一步就会看到(想排到这一轮之后,用 /queue <任务>)"));
|
|
1047
|
+
repl.prompt();
|
|
1048
|
+
try {
|
|
1049
|
+
await ask(line, "steer");
|
|
1050
|
+
}
|
|
1051
|
+
catch (error) {
|
|
1052
|
+
log(c.red(`出错:${error instanceof Error ? error.message : String(error)}`));
|
|
1053
|
+
}
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
1056
|
+
busy++;
|
|
1057
|
+
try {
|
|
1058
|
+
await ask(line);
|
|
1059
|
+
}
|
|
1060
|
+
catch (error) {
|
|
1061
|
+
log(c.red(`出错:${error instanceof Error ? error.message : String(error)}`));
|
|
1062
|
+
}
|
|
1063
|
+
finally {
|
|
1064
|
+
busy--;
|
|
1065
|
+
if (!closing) {
|
|
1066
|
+
log();
|
|
1067
|
+
repl.prompt();
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
});
|
|
1071
|
+
repl.on("close", () => { plainQuestion?.reject(new Error("终端已关闭,配置未保存。")); plainQuestion = undefined; void shutdown(0); });
|
|
1072
|
+
repl.prompt();
|
|
1073
|
+
}
|
|
1074
|
+
/** 选择器只读取已有会话;查看成员不会复制历史,也不会触发模型。 */
|
|
1075
|
+
async function showTerminalConversations(tree = false) {
|
|
1076
|
+
if (configuring)
|
|
1077
|
+
throw new Error("请先完成或取消配置。");
|
|
1078
|
+
if (!terminalUI) {
|
|
1079
|
+
await sessionCommand("/sessions");
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
if (closing || switchingSession)
|
|
1083
|
+
return;
|
|
1084
|
+
const activeId = sessionId;
|
|
1085
|
+
const generation = terminalGeneration;
|
|
1086
|
+
const native = await listNativeConversations(harness, root, context);
|
|
1087
|
+
const sessionSummaries = await conversationList();
|
|
1088
|
+
const summaryById = new Map(sessionSummaries.map((item) => [item.id, item.digest]));
|
|
1089
|
+
if (closing || switchingSession || activeId !== sessionId || generation !== terminalGeneration)
|
|
1090
|
+
return;
|
|
1091
|
+
const items = [
|
|
1092
|
+
...sessionCatalog.list().map((info) => ({
|
|
1093
|
+
id: `session:${info.id}`, title: info.title, createdAt: summaryById.get(info.id)?.firstAt ?? info.createdAt, workdir: info.workdir,
|
|
1094
|
+
lastAt: summaryById.get(info.id)?.lastAt,
|
|
1095
|
+
messageCount: summaryById.get(info.id)?.messageCount,
|
|
1096
|
+
searchText: summaryById.get(info.id)?.text,
|
|
1097
|
+
detail: `${info.id} · ${sessions.has(info.id) ? "已打开" : "历史已保存"} · ${info.workdir}`,
|
|
1098
|
+
current: info.id === sessionId && (!terminalConversation || String(terminalConversation.id) === String(root.id)),
|
|
1099
|
+
})),
|
|
1100
|
+
...native.map((info) => ({ ...info, id: `conversation:${info.id}`,
|
|
1101
|
+
parentId: info.parentId ? `conversation:${info.parentId}` : `session:${sessionId}`,
|
|
1102
|
+
detail: `${String(root.id) === info.id ? "返回总控" : "只读查看 · " + info.detail}`,
|
|
1103
|
+
current: info.id === String(terminalConversation?.id ?? root.id),
|
|
1104
|
+
})),
|
|
1105
|
+
];
|
|
1106
|
+
if (tree)
|
|
1107
|
+
terminalUI.showConversationTree(items);
|
|
1108
|
+
else
|
|
1109
|
+
terminalUI.showConversations(items);
|
|
1110
|
+
}
|
|
1111
|
+
/** Model catalogs are views; only Durable commits change the selected controller model. */
|
|
1112
|
+
async function modelCommand(id = "") {
|
|
1113
|
+
if (configuring)
|
|
1114
|
+
throw new Error("请先完成或取消配置。");
|
|
1115
|
+
if (closing || switchingSession)
|
|
1116
|
+
throw new Error("正在切换会话,请稍后。");
|
|
1117
|
+
if (terminalConversation && String(terminalConversation.id) !== String(root.id))
|
|
1118
|
+
throw new Error("子对话为只读查看;请先 /main 返回总控再切换模型。");
|
|
1119
|
+
const target = root, targetHarness = harness, models = orchestrator.models, provider = orchestrator.ref.provider;
|
|
1120
|
+
const activeId = sessionId, generation = terminalGeneration;
|
|
1121
|
+
const current = () => !closing && !switchingSession && sessionId === activeId && terminalGeneration === generation;
|
|
1122
|
+
const apply = async (selected) => {
|
|
1123
|
+
if (!current())
|
|
1124
|
+
return;
|
|
1125
|
+
activeTerminalCommands++;
|
|
1126
|
+
try {
|
|
1127
|
+
await selectControllerModel(targetHarness, target, models, provider, selected, context);
|
|
1128
|
+
}
|
|
1129
|
+
finally {
|
|
1130
|
+
activeTerminalCommands--;
|
|
1131
|
+
}
|
|
1132
|
+
if (!current())
|
|
1133
|
+
return;
|
|
1134
|
+
terminalUI?.setModel(`${selected.provider}/${selected.id}`);
|
|
1135
|
+
log(`已切换总控模型:${selected.provider}/${selected.id}(当前会话保存,历史与后台任务保留)。`);
|
|
1136
|
+
};
|
|
1137
|
+
if (id) {
|
|
1138
|
+
await apply({ provider, id });
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
const agent = await target.agent(context);
|
|
1142
|
+
if (!terminalUI) {
|
|
1143
|
+
log(`当前总控模型:${agent.model?.provider}/${agent.model?.modelId}`);
|
|
1144
|
+
for (const model of controllerModels(models, provider))
|
|
1145
|
+
log(`${model.id}${model.id === agent.model?.modelId ? " ●" : ""}`);
|
|
1146
|
+
log("/model <模型ID> 切换;中转站可在 orchestrator.modelIds 配置更多模型。");
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
const catalog = await nativeModelCatalog(models, provider, config.orchestrator.discoverModels === true);
|
|
1150
|
+
if (!current())
|
|
1151
|
+
return;
|
|
1152
|
+
const available = catalog.getAvailableSnapshot();
|
|
1153
|
+
if (!available.length)
|
|
1154
|
+
throw new Error("当前总控 provider 没有可用模型,请检查配置和密钥。");
|
|
1155
|
+
terminalUI.showModels(catalog, agent.model ? models.getModel(agent.model.provider, agent.model.modelId) : undefined, config.orchestrator.discoverModels ? [] : available, (selected) => {
|
|
1156
|
+
terminalCommands = terminalCommands.then(() => apply(selected)).catch((error) => { if (current())
|
|
1157
|
+
log(c.red(error instanceof Error ? error.message : String(error))); });
|
|
1158
|
+
});
|
|
1159
|
+
}
|
|
1160
|
+
async function selectTerminalConversation(id) {
|
|
1161
|
+
if (!terminalUI) {
|
|
1162
|
+
log("子对话查看请使用新版终端(npm start)。");
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
if (closing || switchingSession)
|
|
1166
|
+
throw new Error("正在切换会话,请稍后。");
|
|
1167
|
+
if (activeTerminalCommands)
|
|
1168
|
+
throw new Error("当前控制命令尚未完成,请稍后再查看子对话。");
|
|
1169
|
+
switchingSession = true;
|
|
1170
|
+
try {
|
|
1171
|
+
const target = await harness.conversation(Number(id), context);
|
|
1172
|
+
if (!target)
|
|
1173
|
+
throw new Error("当前会话中没有这个子对话。");
|
|
1174
|
+
if (closing || String(target.id) === String(terminalConversation?.id ?? root.id))
|
|
1175
|
+
return;
|
|
1176
|
+
drafts.set(terminalDraftKey(), terminalUI.editor.getExpandedText());
|
|
1177
|
+
terminalConversation = target;
|
|
1178
|
+
await startTui();
|
|
1179
|
+
if (String(target.id) !== String(root.id))
|
|
1180
|
+
log("正在只读查看子对话;/main 返回总控。成员继续在原任务中执行。");
|
|
1181
|
+
}
|
|
1182
|
+
finally {
|
|
1183
|
+
switchingSession = false;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
/** 同一个 Pi TUI 一直存在,切换仅替换 Durable 订阅和界面绑定。 */
|
|
1187
|
+
async function startTui() {
|
|
1188
|
+
const report = (error) => { if (!closing)
|
|
1189
|
+
log(c.red(`出错:${error instanceof Error ? error.message : String(error)}`)); };
|
|
1190
|
+
const creating = !terminalUI;
|
|
1191
|
+
if (!terminalUI) {
|
|
1192
|
+
const ui = new AgentTerminal({
|
|
1193
|
+
workdir: config.workdir, model: orchestrator.describe, web: admin?.url, session: sessionId, conversationId: String(root.id),
|
|
1194
|
+
onSubmit(text) {
|
|
1195
|
+
if (closing)
|
|
1196
|
+
return;
|
|
1197
|
+
const generation = terminalGeneration;
|
|
1198
|
+
const readingChild = !!terminalConversation && String(terminalConversation.id) !== String(root.id);
|
|
1199
|
+
if (text.startsWith("/")) {
|
|
1200
|
+
const run = async () => {
|
|
1201
|
+
if (closing || generation !== terminalGeneration)
|
|
1202
|
+
return;
|
|
1203
|
+
if (switchingSession && text !== "/exit" && text !== "/quit")
|
|
1204
|
+
return log(c.dim("正在切换,命令未执行,请稍后重试。"));
|
|
1205
|
+
// Task-owned 子对话由原派工管理,只允许查看或返回,不改变它的执行。
|
|
1206
|
+
const readCommand = /^(?:\/help|\/history|\/thinking|\/ready|\/main|\/conversations|\/tree|\/taskgraph|\/conversation|\/id|\/sessions?|\/members|\/tasks|\/goal|\/jobs|\/changes|\/diff|\/usage|\/agents|\/web|\/learn|\/repair|\/exit|\/quit)(?:\s|$)/.test(text) && !/^\/jobs\s+cancel/.test(text);
|
|
1207
|
+
if (readingChild && !readCommand)
|
|
1208
|
+
return log(c.yellow("子对话为只读查看;请先 /main 返回总控再执行控制命令。"));
|
|
1209
|
+
const bindsView = /^\/(?:sessions?|conversations|tree|main)(?:\s|$)/.test(text);
|
|
1210
|
+
if (!bindsView)
|
|
1211
|
+
activeTerminalCommands++;
|
|
1212
|
+
try {
|
|
1213
|
+
if (!(await command(text)))
|
|
1214
|
+
log(c.red(`未知命令:${text}`));
|
|
1215
|
+
}
|
|
1216
|
+
catch (error) {
|
|
1217
|
+
report(error);
|
|
1218
|
+
}
|
|
1219
|
+
finally {
|
|
1220
|
+
if (!bindsView)
|
|
1221
|
+
activeTerminalCommands--;
|
|
1222
|
+
}
|
|
1223
|
+
};
|
|
1224
|
+
if (["/abort", "/abort all", "/exit", "/quit"].includes(text))
|
|
1225
|
+
void run();
|
|
1226
|
+
else
|
|
1227
|
+
terminalCommands = terminalCommands.then(run).catch(report);
|
|
1228
|
+
}
|
|
1229
|
+
else {
|
|
1230
|
+
if (switchingSession)
|
|
1231
|
+
return log(c.dim("正在切换,消息未发送,请稍后重试。"));
|
|
1232
|
+
if (readingChild)
|
|
1233
|
+
return log(c.yellow("子对话为只读查看,消息未发送。/main 返回总控继续对话。"));
|
|
1234
|
+
const activeId = sessionId;
|
|
1235
|
+
void ask(text, "steer").catch((error) => { if (sessionId === activeId)
|
|
1236
|
+
report(error); });
|
|
1237
|
+
}
|
|
1238
|
+
},
|
|
1239
|
+
onInterrupt() {
|
|
1240
|
+
void (async () => {
|
|
1241
|
+
if (closing || switchingSession)
|
|
1242
|
+
return;
|
|
1243
|
+
if (terminalConversation && String(terminalConversation.id) !== String(root.id))
|
|
1244
|
+
return log(c.dim("正在只读查看子对话;/main 返回总控,/exit 退出。"));
|
|
1245
|
+
const target = root, targetHarness = harness, generation = terminalGeneration;
|
|
1246
|
+
const live = await targetHarness.snapshot(LiveDoc, target.id, context);
|
|
1247
|
+
if (closing || switchingSession || generation !== terminalGeneration)
|
|
1248
|
+
return;
|
|
1249
|
+
if (live?.run !== undefined) {
|
|
1250
|
+
log(c.yellow("正在中止本轮…(后台任务继续;/abort all 全部中止)"));
|
|
1251
|
+
await target.abort(context);
|
|
1252
|
+
}
|
|
1253
|
+
else
|
|
1254
|
+
await shutdown(0);
|
|
1255
|
+
})().catch(report);
|
|
1256
|
+
},
|
|
1257
|
+
onExit: () => { void shutdown(0).catch(report); },
|
|
1258
|
+
onSessionNext: () => {
|
|
1259
|
+
if (closing || switchingSession)
|
|
1260
|
+
return;
|
|
1261
|
+
const ids = sessionCatalog.list().map((s) => s.id);
|
|
1262
|
+
void sessionCommand(`/session use ${ids[(ids.indexOf(sessionId) + 1) % ids.length]}`).catch(report);
|
|
1263
|
+
},
|
|
1264
|
+
onSessionNew: () => { if (!switchingSession)
|
|
1265
|
+
void sessionCommand("/session new").catch(report); },
|
|
1266
|
+
onConversations: () => { void showTerminalConversations().catch(report); },
|
|
1267
|
+
onTree: () => { void showTerminalConversations(true).catch(report); },
|
|
1268
|
+
onModels: () => { void modelCommand().catch(report); },
|
|
1269
|
+
onConversationSelect: (id) => {
|
|
1270
|
+
if (id.startsWith("session:")) {
|
|
1271
|
+
const target = id.slice(8);
|
|
1272
|
+
void (target === sessionId ? selectTerminalConversation(String(root.id)) : sessionCommand(`/session use ${target}`)).catch(report);
|
|
1273
|
+
}
|
|
1274
|
+
else if (id.startsWith("conversation:"))
|
|
1275
|
+
void selectTerminalConversation(id.slice(13)).catch(report);
|
|
1276
|
+
},
|
|
1277
|
+
});
|
|
1278
|
+
terminalUI = ui;
|
|
1279
|
+
setOutputSink((text) => ui.write(text));
|
|
1280
|
+
ui.start();
|
|
1281
|
+
}
|
|
1282
|
+
const ui = terminalUI;
|
|
1283
|
+
const generation = ++terminalGeneration;
|
|
1284
|
+
stopTerminalStatus();
|
|
1285
|
+
await stopFollowing();
|
|
1286
|
+
stopFollowing = async () => { };
|
|
1287
|
+
if (closing || generation !== terminalGeneration)
|
|
1288
|
+
return;
|
|
1289
|
+
const activeId = sessionId;
|
|
1290
|
+
const activeApp = app;
|
|
1291
|
+
const conversation = terminalConversation ?? root;
|
|
1292
|
+
const currentAgent = await conversation.agent(context);
|
|
1293
|
+
if (closing || generation !== terminalGeneration)
|
|
1294
|
+
return;
|
|
1295
|
+
terminalConversation = conversation;
|
|
1296
|
+
const current = () => !closing && activeId === sessionId && generation === terminalGeneration;
|
|
1297
|
+
ui.bind({ workdir: currentAgent.cwd ?? config.workdir, model: currentAgent.model ? `${currentAgent.model.provider}/${currentAgent.model.modelId}` : orchestrator.describe, web: admin?.url, session: sessionId,
|
|
1298
|
+
conversationId: String(conversation.id), conversationLabel: String(conversation.id) === String(root.id) ? "总控 CID" : "子对话 CID · 只读",
|
|
1299
|
+
}, drafts.get(terminalDraftKey()) ?? "");
|
|
1300
|
+
if (creating)
|
|
1301
|
+
log(c.dim(`${orchestrator.info?.type ?? config.orchestrator.type} · 会话存储:${config.storage}`));
|
|
1302
|
+
const authWarn = orchestratorKeyWarning(config.orchestrator);
|
|
1303
|
+
if (authWarn)
|
|
1304
|
+
log(c.yellow(`⚠ ${authWarn}`));
|
|
1305
|
+
if (pendingChanges(activeApp.changes).length)
|
|
1306
|
+
printChanges(false);
|
|
1307
|
+
let busy = false;
|
|
1308
|
+
let refreshing = false;
|
|
1309
|
+
let refreshAgain = false;
|
|
1310
|
+
async function refresh() {
|
|
1311
|
+
if (!current())
|
|
1312
|
+
return;
|
|
1313
|
+
if (refreshing) {
|
|
1314
|
+
refreshAgain = true;
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
refreshing = true;
|
|
1318
|
+
try {
|
|
1319
|
+
do {
|
|
1320
|
+
refreshAgain = false;
|
|
1321
|
+
const [jobs, budget] = await Promise.all([activeApp.harness.snapshot(Jobs, context), activeApp.harness.snapshot(RunBudget, context)]);
|
|
1322
|
+
if (!current())
|
|
1323
|
+
return;
|
|
1324
|
+
ui.setStatus({ busy, jobs: Object.values(jobs?.jobs ?? {}).filter((j) => j.status === "running").map((j) => `${j.id} ${j.agent}`),
|
|
1325
|
+
spent: budget?.spent ?? 0, budget: config.budget.perRunUsd, pending: pendingChanges(activeApp.changes).length });
|
|
1326
|
+
} while (refreshAgain && current());
|
|
1327
|
+
}
|
|
1328
|
+
catch (error) {
|
|
1329
|
+
if (current())
|
|
1330
|
+
report(error);
|
|
1331
|
+
}
|
|
1332
|
+
finally {
|
|
1333
|
+
refreshing = false;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
const refreshStatus = () => { void refresh(); };
|
|
1337
|
+
activeApp.jobs.on("change", refreshStatus);
|
|
1338
|
+
activeApp.changes.on("change", refreshStatus);
|
|
1339
|
+
stopTerminalStatus = () => { activeApp.jobs.off("change", refreshStatus); activeApp.changes.off("change", refreshStatus); };
|
|
1340
|
+
try {
|
|
1341
|
+
const stop = await watchTerminalState({ harness: activeApp.harness, conversation, context,
|
|
1342
|
+
onConversation(view) { if (!current())
|
|
1343
|
+
return; busy = view.live.busy; ui.applyConversation(view); refreshStatus(); },
|
|
1344
|
+
onTasks(tasks) { if (current())
|
|
1345
|
+
ui.applyTasks(tasks); },
|
|
1346
|
+
onError(error) { if (current())
|
|
1347
|
+
report(error); },
|
|
1348
|
+
});
|
|
1349
|
+
if (!current()) {
|
|
1350
|
+
await stop();
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
stopFollowing = stop;
|
|
1354
|
+
await refresh();
|
|
1355
|
+
}
|
|
1356
|
+
catch (error) {
|
|
1357
|
+
stopTerminalStatus();
|
|
1358
|
+
if (creating) {
|
|
1359
|
+
ui.stop();
|
|
1360
|
+
terminalUI = undefined;
|
|
1361
|
+
terminalConversation = undefined;
|
|
1362
|
+
setOutputSink(undefined);
|
|
1363
|
+
}
|
|
1364
|
+
if (!closing)
|
|
1365
|
+
throw error;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
const oneShot = argv
|
|
1369
|
+
.filter((a) => !a.startsWith("--"))
|
|
1370
|
+
.join(" ")
|
|
1371
|
+
.trim();
|
|
1372
|
+
if (oneShot) {
|
|
1373
|
+
stopFollowing = await follow(root, context);
|
|
1374
|
+
harness.resume(); // 上次进程中断时没跑完的任务,从断点继续
|
|
1375
|
+
await printBanner();
|
|
1376
|
+
log(`\n${c.cyan("你 ›")} ${oneShot}`);
|
|
1377
|
+
const settled = await ask(oneShot);
|
|
1378
|
+
await untilSettled();
|
|
1379
|
+
await shutdown(settled.status === "done" ? 0 : 1);
|
|
1380
|
+
}
|
|
1381
|
+
else {
|
|
1382
|
+
await startWeb();
|
|
1383
|
+
const useTui = flags.has("--tui") && !flags.has("--plain") && process.stdin.isTTY && process.stdout.isTTY && process.env.TERM !== "dumb";
|
|
1384
|
+
if (useTui) {
|
|
1385
|
+
await startTui().catch(async (error) => {
|
|
1386
|
+
log(c.yellow(`新版终端启动失败,回到普通模式:${error instanceof Error ? error.message : String(error)}`));
|
|
1387
|
+
stopFollowing = await follow(root, context);
|
|
1388
|
+
await startRepl();
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
else {
|
|
1392
|
+
if (flags.has("--tui") && !flags.has("--plain"))
|
|
1393
|
+
log(c.dim("当前不是交互终端,使用普通文本模式。"));
|
|
1394
|
+
stopFollowing = await follow(root, context);
|
|
1395
|
+
await startRepl();
|
|
1396
|
+
}
|
|
1397
|
+
harness.resume();
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1401
|
+
await startMain();
|
|
1402
|
+
}
|