@autopilot-agent/cli 0.2.0 → 0.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.
- package/README.md +15 -6
- package/dist/activity-animation.d.ts +5 -0
- package/dist/activity-animation.js +13 -17
- package/dist/browser-client.d.ts +14 -0
- package/dist/browser-client.js +156 -0
- package/dist/composition-root.d.ts +41 -1
- package/dist/composition-root.js +141 -14
- package/dist/context-report.d.ts +9 -4
- package/dist/context-report.js +15 -3
- package/dist/controller.d.ts +81 -4
- package/dist/controller.js +468 -98
- package/dist/design-tokens.d.ts +7 -2
- package/dist/design-tokens.js +11 -3
- package/dist/desktop-status.d.ts +35 -0
- package/dist/desktop-status.js +304 -0
- package/dist/error-diagnostics.d.ts +2 -0
- package/dist/error-diagnostics.js +3 -1
- package/dist/event-projector.d.ts +16 -2
- package/dist/event-projector.js +74 -5
- package/dist/file-mention-budget.d.ts +16 -0
- package/dist/file-mention-budget.js +82 -0
- package/dist/file-mention-context.d.ts +26 -1
- package/dist/file-mention-context.js +70 -22
- package/dist/index.d.ts +1 -1
- package/dist/main.d.ts +3 -0
- package/dist/main.js +213 -12
- package/dist/managed-attach.d.ts +3 -0
- package/dist/managed-attach.js +132 -0
- package/dist/managed-controller.d.ts +49 -0
- package/dist/managed-controller.js +171 -0
- package/dist/orchestration-templates.d.ts +27 -0
- package/dist/orchestration-templates.js +20 -0
- package/dist/parser.d.ts +1 -1
- package/dist/parser.js +510 -2
- package/dist/renderer.js +3 -1
- package/dist/session-summary.d.ts +7 -0
- package/dist/session-summary.js +25 -0
- package/dist/session-title.d.ts +5 -0
- package/dist/session-title.js +10 -0
- package/dist/thread-commands.d.ts +37 -0
- package/dist/thread-commands.js +233 -0
- package/dist/thread-host.d.ts +36 -0
- package/dist/thread-host.js +79 -0
- package/dist/timeline-lines.js +36 -28
- package/dist/tui/app.d.ts +22 -0
- package/dist/tui/app.js +179 -43
- package/dist/tui/approval.d.ts +4 -0
- package/dist/tui/approval.js +13 -4
- package/dist/tui/brand/brand-header.d.ts +1 -3
- package/dist/tui/brand/brand-header.js +6 -8
- package/dist/tui/brand/logo.d.ts +3 -0
- package/dist/tui/brand/logo.js +89 -0
- package/dist/tui/brand/startup.d.ts +18 -0
- package/dist/tui/brand/startup.js +136 -0
- package/dist/tui/constants.d.ts +1 -1
- package/dist/tui/constants.js +1 -1
- package/dist/tui/context.js +1 -3
- package/dist/tui/desktop-resize.d.ts +9 -0
- package/dist/tui/desktop-resize.js +95 -0
- package/dist/tui/format.d.ts +1 -1
- package/dist/tui/format.js +19 -9
- package/dist/tui/hooks/use-file-mention-index.js +9 -4
- package/dist/tui/hooks/use-prompt-input.d.ts +54 -1
- package/dist/tui/hooks/use-prompt-input.js +159 -26
- package/dist/tui/hooks/use-status-view.d.ts +2 -2
- package/dist/tui/hooks/use-status-view.js +38 -11
- package/dist/tui/hooks/use-viewport.d.ts +2 -1
- package/dist/tui/hooks/use-viewport.js +15 -8
- package/dist/tui/inline-output.d.ts +17 -0
- package/dist/tui/inline-output.js +31 -0
- package/dist/tui/input/clipboard-image.d.ts +17 -0
- package/dist/tui/input/clipboard-image.js +117 -0
- package/dist/tui/input-area.d.ts +12 -1
- package/dist/tui/input-area.js +28 -8
- package/dist/tui/lifecycle.d.ts +1 -1
- package/dist/tui/lifecycle.js +84 -16
- package/dist/tui/markdown/diff.d.ts +1 -1
- package/dist/tui/markdown/diff.js +28 -1
- package/dist/tui/performance-diagnostics.js +2 -0
- package/dist/tui/pickers/permission.js +1 -1
- package/dist/tui/pickers/slash.d.ts +11 -2
- package/dist/tui/pickers/slash.js +21 -7
- package/dist/tui/prompt-input.d.ts +2 -0
- package/dist/tui/prompt-input.js +6 -4
- package/dist/tui/render-mode.d.ts +8 -4
- package/dist/tui/render-mode.js +17 -11
- package/dist/tui/run.js +53 -55
- package/dist/tui/session-manager.d.ts +116 -0
- package/dist/tui/session-manager.js +384 -0
- package/dist/tui/session-workspace.d.ts +9 -0
- package/dist/tui/session-workspace.js +383 -0
- package/dist/tui/status-line.d.ts +4 -0
- package/dist/tui/status-line.js +34 -13
- package/dist/tui/store.d.ts +3 -1
- package/dist/tui/store.js +60 -14
- package/dist/tui/timeline/live.js +2 -3
- package/dist/tui/timeline/progress.js +3 -2
- package/dist/tui/timeline/static-timeline.js +1 -2
- package/dist/tui/timeline/turn.js +3 -2
- package/dist/tui/transcript.d.ts +2 -1
- package/dist/tui/transcript.js +43 -5
- package/dist/tui/trust-dialog.d.ts +3 -0
- package/dist/tui/trust-dialog.js +23 -2
- package/dist/tui/types.d.ts +18 -1
- package/dist/tui/types.js +4 -1
- package/dist/tui/viewport/selection.d.ts +2 -2
- package/dist/tui/viewport/selection.js +13 -6
- package/dist/tui/viewport/sources.js +13 -14
- package/dist/types.d.ts +160 -3
- package/package.json +4 -4
package/dist/main.js
CHANGED
|
@@ -5,17 +5,22 @@
|
|
|
5
5
|
* 入口只负责 argv、Composition Root、Plain Controller 和进程生命周期的编排;
|
|
6
6
|
* Session、Turn、审批、恢复和持久化规则全部委托给 Core Runtime。
|
|
7
7
|
*/
|
|
8
|
+
import { createCliSessionManager } from "./tui/session-manager.js";
|
|
9
|
+
import { createDesktopStatus } from "./desktop-status.js";
|
|
10
|
+
import { executeBrowserCommand, getBrowserErrorCode } from "./browser-client.js";
|
|
11
|
+
import { startCliStartupLogo } from "./tui/brand/startup.js";
|
|
8
12
|
import { WEB_SEARCH_DATA_FLOW_NOTICE } from "@autopilot-agent/presentation";
|
|
9
13
|
import path from "node:path";
|
|
10
14
|
import fs from "node:fs";
|
|
11
15
|
import readline from "node:readline";
|
|
12
|
-
import {
|
|
13
|
-
import { AgentRuntimeError, WorkspaceTrustError, } from "@autopilot-agent/core";
|
|
16
|
+
import { fileURLToPath } from "node:url";
|
|
17
|
+
import { AgentRuntimeError, ThreadServiceError, WorkspaceTrustError, } from "@autopilot-agent/core";
|
|
14
18
|
import { createCliCompositionRoot } from "./composition-root.js";
|
|
15
19
|
import { createCliController } from "./controller.js";
|
|
16
|
-
import { classifyCliError } from "./error-diagnostics.js";
|
|
20
|
+
import { classifyCliError, CLI_THREAD_RECOVERY_HINT } from "./error-diagnostics.js";
|
|
17
21
|
import { parseArgv, parseSlashAction, renderHelp } from "./parser.js";
|
|
18
22
|
import { createPlainRenderer } from "./renderer.js";
|
|
23
|
+
import { CliThreadInputError, executeThreadCommand } from "./thread-commands.js";
|
|
19
24
|
import { runCliTui, runCliTrustDialog } from "./tui.js";
|
|
20
25
|
/** 将宿主信号映射为固定 CLI 退出码。 */
|
|
21
26
|
export function exitCodeForSignal(signal) {
|
|
@@ -31,11 +36,26 @@ function writeControllerResult(result, streams) {
|
|
|
31
36
|
}
|
|
32
37
|
/** 将 Runtime/Trust 异常收窄为不泄露绝对路径、凭据或原始输入的诊断。 */
|
|
33
38
|
function formatCliError(error) {
|
|
39
|
+
const browserCode = getBrowserErrorCode(error);
|
|
40
|
+
if (browserCode)
|
|
41
|
+
return browserCode;
|
|
34
42
|
const classification = classifyCliError(error);
|
|
35
43
|
if (classification.category === "config_directory")
|
|
36
44
|
return classification.code;
|
|
45
|
+
if (classification.category === "node_state") {
|
|
46
|
+
const messages = {
|
|
47
|
+
STATE_SCHEMA_VERSION_UNSUPPORTED: "状态数据来自不支持的版本,请更新程序后重试;现有数据已保留",
|
|
48
|
+
STATE_SCHEMA_BUSY: "状态数据正在使用或升级,请停止其他运行实例后重试",
|
|
49
|
+
STATE_SCHEMA_MIGRATION_FAILED: "状态升级未完成,原数据和恢复备份已保留,请停止其他运行实例后重试;仍失败请联系支持",
|
|
50
|
+
STATE_SCHEMA_MIGRATION_MISSING: "缺少状态升级步骤,请更新程序后重试;现有数据已保留",
|
|
51
|
+
STATE_SCHEMA_RECOVERY_REQUIRED: "状态需要恢复,原数据已保留,请停止其他运行实例后重试;仍失败请联系支持",
|
|
52
|
+
};
|
|
53
|
+
return `${classification.code}${Object.hasOwn(messages, classification.code) ? `: ${messages[classification.code]}` : ""}`;
|
|
54
|
+
}
|
|
37
55
|
if (error instanceof WorkspaceTrustError)
|
|
38
56
|
return `WORKSPACE_TRUST_REQUIRED: ${error.status}`;
|
|
57
|
+
if (error instanceof AgentRuntimeError && error.code === "THREAD_RECOVERY_REQUIRED")
|
|
58
|
+
return `${error.code}: ${CLI_THREAD_RECOVERY_HINT}`;
|
|
39
59
|
if (error instanceof AgentRuntimeError)
|
|
40
60
|
return `${error.code}: ${sanitizeErrorMessage(error.message)}`;
|
|
41
61
|
return "CLI_RUNTIME_ERROR";
|
|
@@ -72,6 +92,18 @@ function sanitizeManagementString(value) {
|
|
|
72
92
|
.replace(/(?:[A-Za-z]:[\\/]|\\\\|\/(?:Users|home|private|tmp|var|mnt|workspace|Volumes)\/)[^\s"'`]+/gu, "[path]")
|
|
73
93
|
.replace(/\b(api[_-]?key|access[_-]?token|password|secret|dsn)\s*[:=]\s*[^\s,;]+/giu, "$1=[redacted]");
|
|
74
94
|
}
|
|
95
|
+
/** 协作结果直接输出 JSON;内容已由 Core 做安全投影与限额,这里不改写正文。 */
|
|
96
|
+
function writeThreadResult(streams, value) {
|
|
97
|
+
streams.stdout.write(`${JSON.stringify(value)}\n`);
|
|
98
|
+
}
|
|
99
|
+
/** 读取全部 stdin;只在命令显式要求 --message-stdin 时调用,避免误吞交互输入。 */
|
|
100
|
+
async function readStdinText(streams) {
|
|
101
|
+
const input = streams.stdin ?? process.stdin;
|
|
102
|
+
let text = "";
|
|
103
|
+
for await (const chunk of input)
|
|
104
|
+
text += String(chunk);
|
|
105
|
+
return text;
|
|
106
|
+
}
|
|
75
107
|
/** 将 Core 安全 JobView 补充独立命令所需身份,不读取命令、路径、PID 或 owner。 */
|
|
76
108
|
function summarizeJob(job, view) {
|
|
77
109
|
return {
|
|
@@ -140,7 +172,7 @@ async function ensureProject(runtime, workspaceRoot) {
|
|
|
140
172
|
return runtime.projects.create({ name: path.basename(workspaceRoot) || "project", workspaceRoot });
|
|
141
173
|
}
|
|
142
174
|
/** 读取指定 Session 或创建当前 Project 下的新 Session。 */
|
|
143
|
-
async function ensureChatSession(runtime, project, sessionId,
|
|
175
|
+
export async function ensureChatSession(runtime, project, sessionId, environment = process.env) {
|
|
144
176
|
if (sessionId) {
|
|
145
177
|
const session = await runtime.sessions.get(sessionId);
|
|
146
178
|
if (!session)
|
|
@@ -149,15 +181,20 @@ async function ensureChatSession(runtime, project, sessionId, prompt) {
|
|
|
149
181
|
throw new AgentRuntimeError("INVALID_INPUT", "Session 不属于当前受信任 Project");
|
|
150
182
|
return session;
|
|
151
183
|
}
|
|
184
|
+
const permission = environment.AUTOPILOT_DESKTOP_AP_PERMISSION;
|
|
185
|
+
if (permission !== undefined && !["ask", "auto_approve", "full_access"].includes(permission))
|
|
186
|
+
throw new AgentRuntimeError("INVALID_INPUT", "Desktop 启动权限无效");
|
|
152
187
|
return runtime.sessions.create({
|
|
153
188
|
projectId: project.id,
|
|
154
|
-
|
|
189
|
+
...(permission ? { defaultRunConfig: { permissionMode: permission } } : {}),
|
|
190
|
+
// 统一由Controller在首个有效交互时建立短标题,成功回答后沿Web范式更新。
|
|
191
|
+
title: undefined,
|
|
155
192
|
});
|
|
156
193
|
}
|
|
157
194
|
/** 读取指定或最近的可恢复 Session;没有可用 Session 时返回稳定错误。 */
|
|
158
195
|
async function selectResumeSession(runtime, project, sessionId) {
|
|
159
196
|
if (sessionId)
|
|
160
|
-
return ensureChatSession(runtime, project, sessionId
|
|
197
|
+
return ensureChatSession(runtime, project, sessionId);
|
|
161
198
|
const sessions = (await runtime.sessions.list())
|
|
162
199
|
.filter(function selectProjectSession(item) { return !item.projectId || item.projectId === project.id; })
|
|
163
200
|
.sort(function sortRecent(left, right) { return right.updatedAt - left.updatedAt; });
|
|
@@ -242,9 +279,80 @@ async function runInputLoop(controller, format, streams, signalSource, showPromp
|
|
|
242
279
|
signalSource.removeListener("SIGTERM", handleSigterm);
|
|
243
280
|
}
|
|
244
281
|
}
|
|
282
|
+
/**
|
|
283
|
+
* 执行协作薄命令。
|
|
284
|
+
*
|
|
285
|
+
* 只绑定当前 Project 并复用 Runtime 的同一份 Ports;不启动常驻 Runner,
|
|
286
|
+
* 因此回执只表示消息已接受,执行仍取决于是否有在线宿主。
|
|
287
|
+
*/
|
|
288
|
+
async function executeThreadInvocation(command, root, runtime, workspaceRoot, streams, signalSource) {
|
|
289
|
+
// 协作组绑定到已存在的 Project;读取命令不为查询新建 Project。
|
|
290
|
+
const project = (await runtime.projects.list()).find(function matchWorkspace(item) { return item.workspaceRoot === workspaceRoot; });
|
|
291
|
+
if (!project) {
|
|
292
|
+
streams.stderr.write("THREADS_UNAVAILABLE: 当前工作区尚未建立 Project\n");
|
|
293
|
+
return 1;
|
|
294
|
+
}
|
|
295
|
+
root.bindThreadsProject(project.id);
|
|
296
|
+
const threads = root.createHumanThreads();
|
|
297
|
+
const controller = new AbortController();
|
|
298
|
+
let requestedExitCode;
|
|
299
|
+
/** 中断只结束本地观察或等待,不向任何目标提交取消。 */
|
|
300
|
+
function handleSignal(signal) {
|
|
301
|
+
requestedExitCode = exitCodeForSignal(signal);
|
|
302
|
+
controller.abort();
|
|
303
|
+
}
|
|
304
|
+
function handleSigint() { handleSignal("SIGINT"); }
|
|
305
|
+
function handleSigterm() { handleSignal("SIGTERM"); }
|
|
306
|
+
signalSource.on("SIGINT", handleSigint);
|
|
307
|
+
signalSource.on("SIGTERM", handleSigterm);
|
|
308
|
+
try {
|
|
309
|
+
const executed = await executeThreadCommand(command, {
|
|
310
|
+
threads,
|
|
311
|
+
readFile: function readFile(file) { return fs.promises.readFile(file, "utf8"); },
|
|
312
|
+
readStdin: function readStdin() { return readStdinText(streams); },
|
|
313
|
+
write: function write(line) { streams.stdout.write(`${line}\n`); },
|
|
314
|
+
signal: controller.signal,
|
|
315
|
+
});
|
|
316
|
+
if (executed.result !== undefined)
|
|
317
|
+
writeThreadResult(streams, executed.result);
|
|
318
|
+
return requestedExitCode ?? executed.exitCode;
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
if (error instanceof CliThreadInputError) {
|
|
322
|
+
streams.stderr.write(`${error.message}\n`);
|
|
323
|
+
return 2;
|
|
324
|
+
}
|
|
325
|
+
if (error instanceof ThreadServiceError) {
|
|
326
|
+
// 参数类错误按 usage 退出码,其余按运行期失败;错误码本身足以定位,不回显路径。
|
|
327
|
+
streams.stderr.write(`${error.code}\n`);
|
|
328
|
+
return error.code === "INVALID_INPUT" || error.code === "MODEL_NOT_FOUND" ? 2 : 1;
|
|
329
|
+
}
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
332
|
+
finally {
|
|
333
|
+
signalSource.removeListener("SIGINT", handleSigint);
|
|
334
|
+
signalSource.removeListener("SIGTERM", handleSigterm);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
245
337
|
/** 执行已经通过 parser 校验的 CLI 命令。 */
|
|
246
|
-
async function executeInvocation(invocation, streams, dependencies) {
|
|
338
|
+
async function executeInvocation(invocation, streams, dependencies, desktopStatus) {
|
|
247
339
|
const command = invocation.command;
|
|
340
|
+
if (command.type === "browser") {
|
|
341
|
+
const abort = new AbortController();
|
|
342
|
+
const signals = dependencies.signalSource ?? process;
|
|
343
|
+
/** 命令退出只取消此动作,不自动重试或执行其他Runtime任务。 */
|
|
344
|
+
function cancel() { abort.abort(); }
|
|
345
|
+
signals.on("SIGINT", cancel);
|
|
346
|
+
signals.on("SIGTERM", cancel);
|
|
347
|
+
try {
|
|
348
|
+
writeManagementResult(streams, await executeBrowserCommand(command.operation, command.permit, abort.signal));
|
|
349
|
+
return 0;
|
|
350
|
+
}
|
|
351
|
+
finally {
|
|
352
|
+
signals.removeListener("SIGINT", cancel);
|
|
353
|
+
signals.removeListener("SIGTERM", cancel);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
248
356
|
const workspaceRoot = invocation.host.workspaceRoot ?? (command.type === "project_open" ? command.path : undefined);
|
|
249
357
|
const rootFactory = dependencies.createCompositionRoot ?? createCliCompositionRoot;
|
|
250
358
|
const root = rootFactory({
|
|
@@ -360,8 +468,23 @@ async function executeInvocation(invocation, streams, dependencies) {
|
|
|
360
468
|
writeManagementResult(streams, { serverName: server.serverName, approved: false, revoked: await root.revokeMcp(trust.workspaceRoot, server.serverName) });
|
|
361
469
|
return 0;
|
|
362
470
|
}
|
|
363
|
-
const
|
|
471
|
+
const startup = (command.type === "chat" || command.type === "resume") && command.output === "interactive" && hasTty
|
|
472
|
+
? startCliStartupLogo(streams.stdout, input)
|
|
473
|
+
: undefined;
|
|
474
|
+
let runtime;
|
|
364
475
|
try {
|
|
476
|
+
runtime = await root.createRuntime(trust.workspaceRoot);
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
startup?.dispose();
|
|
480
|
+
throw error;
|
|
481
|
+
}
|
|
482
|
+
let threadHost;
|
|
483
|
+
let sessionManager;
|
|
484
|
+
try {
|
|
485
|
+
if (command.type === "thread") {
|
|
486
|
+
return await executeThreadInvocation(command.command, root, runtime, trust.workspaceRoot, streams, signalSource);
|
|
487
|
+
}
|
|
365
488
|
if (command.type === "job_list" || command.type === "job_show" || command.type === "job_output" || command.type === "job_kill") {
|
|
366
489
|
if (command.type === "job_list") {
|
|
367
490
|
const jobs = await runtime.jobs.list(trust.workspaceRoot);
|
|
@@ -439,13 +562,19 @@ async function executeInvocation(invocation, streams, dependencies) {
|
|
|
439
562
|
}
|
|
440
563
|
const configurationError = root.getStartupConfigurationError?.();
|
|
441
564
|
if (configurationError) {
|
|
565
|
+
startup?.dispose();
|
|
442
566
|
streams.stderr.write(`${configurationError}\n`);
|
|
443
567
|
return 1;
|
|
444
568
|
}
|
|
445
569
|
const project = await ensureProject(runtime, trust.workspaceRoot);
|
|
570
|
+
// 协作范围按 Project 绑定;常驻宿主发现已启用组后才接管驱动,未启用时保持轻量复查。
|
|
571
|
+
root.bindThreadsProject(project.id);
|
|
572
|
+
threadHost = root.createThreadHost(runtime, function reportThreadHostError(error, continuation) { const classification = classifyCliError(error); streams.stderr.write(`THREAD_HOST_ERROR ${classification.category}/${classification.code}\n`); const diagnostic = continuation?.failureDiagnostic; const notice = diagnostic ? `会话 ${continuation.threadId} / Turn ${continuation.expectedTurnId} / 控制 ${continuation.controlId}:决定已保存但恢复失败(${diagnostic.category}/${diagnostic.code},${diagnostic.stage},已观察启动=${diagnostic.started})` : `关联任务状态提交失败(${classification.category}/${classification.code}),请查看目标会话确认执行状态`; streams.stderr.write(`${notice}\n`); sessionManager?.selected().store.addNotice(notice); }, function observeDesktopExecution(input) { desktopStatus?.track(input.threadId); });
|
|
573
|
+
if (!startup)
|
|
574
|
+
threadHost.start();
|
|
446
575
|
const session = command.type === "resume"
|
|
447
576
|
? await selectResumeSession(runtime, project, command.sessionId)
|
|
448
|
-
: await ensureChatSession(runtime, project, command.sessionId
|
|
577
|
+
: await ensureChatSession(runtime, project, command.sessionId);
|
|
449
578
|
const renderer = command.output === "interactive" && hasTty
|
|
450
579
|
? { format: "text", render: function renderTuiEvent() { return ""; } }
|
|
451
580
|
: createPlainRenderer(command.output === "jsonl" ? "jsonl" : "text");
|
|
@@ -457,8 +586,24 @@ async function executeInvocation(invocation, streams, dependencies) {
|
|
|
457
586
|
getRuntimeStatusDefaults: root.getRuntimeStatusDefaults,
|
|
458
587
|
listSkills: root.listSkills,
|
|
459
588
|
resolveSkill: root.resolveSkill,
|
|
589
|
+
registerExecution: function registerExecution(input) { desktopStatus?.track(input.threadId); return threadHost.registerExecution(input); },
|
|
460
590
|
});
|
|
461
|
-
const
|
|
591
|
+
const statusWorkspace = root.getDesktopStatusWorkspace?.();
|
|
592
|
+
if (statusWorkspace)
|
|
593
|
+
desktopStatus?.bind({
|
|
594
|
+
workspace: statusWorkspace,
|
|
595
|
+
selected: function selected() { return sessionManager?.selected().sessionId ?? session.id; },
|
|
596
|
+
entries: function entries() { return sessionManager?.entries() ?? [{ sessionId: session.id, opened: true }]; },
|
|
597
|
+
executions: function executions() { return threadHost?.listExecutions() ?? []; },
|
|
598
|
+
read: function read(sessionId, signal) {
|
|
599
|
+
const entry = sessionManager?.entries().find(function target(item) { return item.sessionId === sessionId; });
|
|
600
|
+
if (entry?.executionView && !entry.controller.isExecuting?.() && Date.now() - (entry.executionViewReadAt ?? 0) < 750)
|
|
601
|
+
return Promise.resolve({ status: entry.executionView.status, executionView: entry.executionView });
|
|
602
|
+
return root.readSessionSummary(sessionId, signal);
|
|
603
|
+
},
|
|
604
|
+
recovery: function recovery(sessionId, turnId) { return runtime.turns.getRecoverableState({ sessionId, turnId }); },
|
|
605
|
+
});
|
|
606
|
+
const recoverable = command.type === "chat" && !command.prompt && (command.output !== "interactive" || !hasTty)
|
|
462
607
|
? await runtime.turns.getRecoverableState({ sessionId: session.id })
|
|
463
608
|
: undefined;
|
|
464
609
|
if (recoverable?.recoverable && recoverable.status === "awaiting_user_input") {
|
|
@@ -472,7 +617,44 @@ async function executeInvocation(invocation, streams, dependencies) {
|
|
|
472
617
|
: command.prompt
|
|
473
618
|
? { type: "start", content: command.prompt }
|
|
474
619
|
: undefined;
|
|
620
|
+
sessionManager = createCliSessionManager({
|
|
621
|
+
runtime, projectId: project.id, initialSession: session, initialController: controller,
|
|
622
|
+
createController: function createForSession(sessionId) { return createCliController({ runtime, renderer, sessionId, workspaceRoot: trust.workspaceRoot, getRuntimeStatusDefaults: root.getRuntimeStatusDefaults, listSkills: root.listSkills, resolveSkill: root.resolveSkill, registerExecution: function registerExecution(input) { desktopStatus?.track(input.threadId); return threadHost.registerExecution(input); } }); },
|
|
623
|
+
/** 通过既有人类只读目录查询创建/关联事实,分页不启动任何目标。 */
|
|
624
|
+
readRelations: async function readRelations(sessionId, signal) {
|
|
625
|
+
signal?.throwIfAborted();
|
|
626
|
+
const threads = root.createHumanThreads();
|
|
627
|
+
const { group } = await threads.groupOf({ protocolVersion: 1, threadId: sessionId });
|
|
628
|
+
signal?.throwIfAborted();
|
|
629
|
+
if (!group)
|
|
630
|
+
return [];
|
|
631
|
+
const items = [];
|
|
632
|
+
let cursor;
|
|
633
|
+
do {
|
|
634
|
+
signal?.throwIfAborted();
|
|
635
|
+
const page = await threads.list({ protocolVersion: 1, groupId: group.groupId, limit: 100, cursor });
|
|
636
|
+
for (const item of page.items) {
|
|
637
|
+
const parentThreadId = item.parentThreadId ?? (item.threadId === group.rootThreadId ? null : group.rootThreadId);
|
|
638
|
+
if (parentThreadId !== sessionId)
|
|
639
|
+
continue;
|
|
640
|
+
signal?.throwIfAborted();
|
|
641
|
+
const summary = await root.readSessionSummary(item.threadId, signal);
|
|
642
|
+
if (summary)
|
|
643
|
+
items.push({ threadId: item.threadId, parentThreadId, title: summary.title, status: summary.status, activeTurnId: summary.currentTurnId ?? summary.activeTurnId, executionView: summary.executionView });
|
|
644
|
+
}
|
|
645
|
+
cursor = page.nextCursor;
|
|
646
|
+
} while (cursor);
|
|
647
|
+
return items;
|
|
648
|
+
},
|
|
649
|
+
readDirectoryPage: function directory(input) { return root.readSessionDirectoryPage(project.id, input); },
|
|
650
|
+
readSummary: root.readSessionSummary,
|
|
651
|
+
readEventPage: root.readSessionEventPage,
|
|
652
|
+
});
|
|
653
|
+
await startup?.finish();
|
|
654
|
+
threadHost.start();
|
|
655
|
+
sessionManager.start();
|
|
475
656
|
const tuiResult = await runCliTui({
|
|
657
|
+
sessionManager,
|
|
476
658
|
controller,
|
|
477
659
|
sessionId: session.id,
|
|
478
660
|
workspaceRoot: trust.workspaceRoot,
|
|
@@ -514,11 +696,25 @@ async function executeInvocation(invocation, streams, dependencies) {
|
|
|
514
696
|
return resumed.exitCode;
|
|
515
697
|
}
|
|
516
698
|
finally {
|
|
699
|
+
startup?.dispose();
|
|
700
|
+
const sessionsStopped = await sessionManager?.stop();
|
|
701
|
+
const stopReport = await threadHost?.stop();
|
|
702
|
+
if (sessionsStopped)
|
|
703
|
+
streams.stderr.write(`宿主退出:确认停止=${sessionsStopped.stopped.length} 等待审批或输入=${sessionsStopped.waiting.length} 可恢复=${sessionsStopped.recoverable.length} 未确认=${sessionsStopped.unconfirmed.length}\n`);
|
|
704
|
+
// 停机报告只陈述事实:取消与未确认项必须显式可见,不能写成目标已完成。
|
|
705
|
+
if (stopReport) {
|
|
706
|
+
streams.stderr.write(`thread runner stopped: cancelled=${stopReport.cancelledTurnIds.length} unconfirmed=${stopReport.unconfirmedTurnIds.length} waiting=${stopReport.waitingTurnIds?.length ?? 0} undelivered=${stopReport.pendingMessageIds?.length ?? 0} recoverable=${stopReport.recoverableTurnIds?.length ?? 0}\n`);
|
|
707
|
+
}
|
|
708
|
+
await desktopStatus?.flush();
|
|
517
709
|
await runtime.shutdown?.();
|
|
518
710
|
}
|
|
519
711
|
}
|
|
520
712
|
/** 执行 Step 5.3 CLI 入口并返回固定退出码。 */
|
|
521
713
|
export async function main(argv = process.argv.slice(2), streams = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin }, dependencies = {}) {
|
|
714
|
+
if (argv.length === 1 && argv[0] === "managed-attach") {
|
|
715
|
+
const { runManagedAttach } = await import("./managed-attach.js");
|
|
716
|
+
return runManagedAttach();
|
|
717
|
+
}
|
|
522
718
|
const parsed = parseArgv(argv);
|
|
523
719
|
if (parsed.kind === "help") {
|
|
524
720
|
streams.stdout.write(`${parsed.text}\n`);
|
|
@@ -528,15 +724,20 @@ export async function main(argv = process.argv.slice(2), streams = { stdout: pro
|
|
|
528
724
|
streams.stderr.write(`${parsed.message}\n\n${renderHelp()}\n`);
|
|
529
725
|
return 2;
|
|
530
726
|
}
|
|
727
|
+
const desktopStatus = parsed.invocation.command.type === "chat" || parsed.invocation.command.type === "resume" ? createDesktopStatus() : undefined;
|
|
531
728
|
try {
|
|
532
|
-
return await executeInvocation(parsed.invocation, streams, dependencies);
|
|
729
|
+
return await executeInvocation(parsed.invocation, streams, dependencies, desktopStatus);
|
|
533
730
|
}
|
|
534
731
|
catch (error) {
|
|
535
732
|
streams.stderr.write(`${formatCliError(error)}\n`);
|
|
536
733
|
return 1;
|
|
537
734
|
}
|
|
735
|
+
finally {
|
|
736
|
+
await desktopStatus?.stop();
|
|
737
|
+
}
|
|
538
738
|
}
|
|
539
|
-
|
|
739
|
+
// npm workspace 联接入口与直接入口统一真实路径,作为模块导入时仍不启动 CLI。
|
|
740
|
+
if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1])) {
|
|
540
741
|
main().then(function finish(exitCode) {
|
|
541
742
|
process.exitCode = exitCode;
|
|
542
743
|
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/** 受管 AP 附着入口:在真实 PTY 复用完整 Ink TUI,通过认证通道操作原会话。 */
|
|
2
|
+
import { createConnection } from "node:net";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { createManagedCliController } from "./managed-controller.js";
|
|
6
|
+
import { createCliTuiStore, runCliTui, runCliTrustDialog } from "./tui.js";
|
|
7
|
+
/** 私有能力仅用于认证;TUI和Controller不创建第二个Runtime或自由Session。 */
|
|
8
|
+
export async function runManagedAttach() {
|
|
9
|
+
const port = Number(process.env.AUTOPILOT_MANAGED_PORT);
|
|
10
|
+
const token = process.env.AUTOPILOT_MANAGED_TOKEN;
|
|
11
|
+
const role = process.env.AUTOPILOT_MANAGED_ROLE === "executor" ? "executor" : "controller";
|
|
12
|
+
delete process.env.AUTOPILOT_MANAGED_TOKEN;
|
|
13
|
+
delete process.env.AUTOPILOT_MANAGED_PORT;
|
|
14
|
+
delete process.env.AUTOPILOT_MANAGED_ROLE;
|
|
15
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || !token || !process.stdin.isTTY || !process.stdout.isTTY)
|
|
16
|
+
return 1;
|
|
17
|
+
const socket = createConnection({ host: "127.0.0.1", port });
|
|
18
|
+
const pending = new Map();
|
|
19
|
+
const store = createCliTuiStore();
|
|
20
|
+
const signals = new EventEmitter();
|
|
21
|
+
let buffer = "";
|
|
22
|
+
let closed = false;
|
|
23
|
+
let cursor;
|
|
24
|
+
let status = "";
|
|
25
|
+
let observedSessionId;
|
|
26
|
+
/** 唯一请求身份保持到回包;未知提交不自动重试。 */
|
|
27
|
+
function request(operation, extra = {}) {
|
|
28
|
+
if (closed)
|
|
29
|
+
return Promise.reject(new Error("受管会话连接中断;请重新连接终端,原 Run 继续保留。"));
|
|
30
|
+
const id = randomUUID();
|
|
31
|
+
return new Promise(function wait(resolve, reject) { pending.set(id, { resolve, reject }); socket.write(JSON.stringify({ id, token, operation, ...extra }) + "\n"); });
|
|
32
|
+
}
|
|
33
|
+
const controller = createManagedCliController(request, function notice(text) { store.addNotice(text); }, role);
|
|
34
|
+
socket.setEncoding("utf8");
|
|
35
|
+
socket.on("data", function receive(data) {
|
|
36
|
+
buffer += data;
|
|
37
|
+
if (buffer.length > 2 * 1024 * 1024) {
|
|
38
|
+
socket.destroy();
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
while (buffer.includes("\n")) {
|
|
42
|
+
const end = buffer.indexOf("\n");
|
|
43
|
+
const line = buffer.slice(0, end);
|
|
44
|
+
buffer = buffer.slice(end + 1);
|
|
45
|
+
try {
|
|
46
|
+
const frame = JSON.parse(line);
|
|
47
|
+
const item = pending.get(frame.id);
|
|
48
|
+
if (!item)
|
|
49
|
+
continue;
|
|
50
|
+
pending.delete(frame.id);
|
|
51
|
+
if (frame.error)
|
|
52
|
+
item.reject(new Error(frame.error));
|
|
53
|
+
else
|
|
54
|
+
item.resolve(frame.result);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
socket.destroy();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
socket.on("error", function failed() { store.addNotice("主控连接失败,不会另开自由会话。"); });
|
|
62
|
+
socket.on("close", function disconnected() { closed = true; for (const item of pending.values())
|
|
63
|
+
item.reject(new Error("连接中断,提交状态未知;不自动重发。")); pending.clear(); signals.emit("SIGTERM"); });
|
|
64
|
+
/** 原终端信号只结束客户端,不能停止Run。 */
|
|
65
|
+
function interrupt() { signals.emit("SIGINT"); }
|
|
66
|
+
/** 应用关闭时交原TUI恢复终端。 */
|
|
67
|
+
function terminate() { signals.emit("SIGTERM"); }
|
|
68
|
+
process.on("SIGINT", interrupt);
|
|
69
|
+
process.on("SIGTERM", terminate);
|
|
70
|
+
/** 持久事件通过原Controller/Store进入完整TUI;无事件时不重放历史或逐行刷屏。 */
|
|
71
|
+
function update(value) {
|
|
72
|
+
if (value.sessionId && value.sessionId !== observedSessionId) {
|
|
73
|
+
observedSessionId = value.sessionId;
|
|
74
|
+
cursor = undefined;
|
|
75
|
+
}
|
|
76
|
+
if (role === "executor" && value.task)
|
|
77
|
+
store.recordTask(value.task.id, value.task.content);
|
|
78
|
+
if (value.status !== status) {
|
|
79
|
+
status = value.status;
|
|
80
|
+
store.addNotice(status);
|
|
81
|
+
}
|
|
82
|
+
for (const rejection of value.queueRejections ?? [])
|
|
83
|
+
store.rejectPendingPrompt(rejection.inputId, rejection.message);
|
|
84
|
+
controller.update(value);
|
|
85
|
+
store.syncProjection(controller.getProjection());
|
|
86
|
+
cursor = value.page?.nextCursor ?? value.page?.cursor ?? cursor;
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
let initial = await request("read");
|
|
90
|
+
if (initial.trustRequired) {
|
|
91
|
+
await request("ready");
|
|
92
|
+
const decision = await runCliTrustDialog({ workspaceRoot: initial.workspaceRoot, streams: { stdout: process.stdout, stdin: process.stdin }, signalSource: signals, env: process.env });
|
|
93
|
+
if (decision !== "granted")
|
|
94
|
+
return 0;
|
|
95
|
+
await request("input", { text: "/trust", requestId: randomUUID() });
|
|
96
|
+
initial = await request("read");
|
|
97
|
+
}
|
|
98
|
+
if (!initial.sessionId || !initial.workspaceRoot)
|
|
99
|
+
throw new Error("受管会话尚未连接,请重试。");
|
|
100
|
+
update(initial);
|
|
101
|
+
const running = runCliTui({ controller, store, managedPromptBackground: true, sessionId: initial.sessionId, workspaceRoot: initial.workspaceRoot, streams: { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin }, signalSource: signals, closeWhenIdle: false, env: process.env });
|
|
102
|
+
await request("ready");
|
|
103
|
+
/** 串行只读分页;输入编辑在Ink本地完成,不等待网络回包。 */
|
|
104
|
+
async function poll() {
|
|
105
|
+
while (!closed) {
|
|
106
|
+
try {
|
|
107
|
+
const value = await request("read", { cursor });
|
|
108
|
+
update(value);
|
|
109
|
+
if (value.page?.nextCursor)
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
if (!closed)
|
|
114
|
+
store.addNotice(error instanceof Error ? error.message : "主控读取失败");
|
|
115
|
+
}
|
|
116
|
+
await new Promise(function delay(resolve) { setTimeout(resolve, 750); });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
void poll();
|
|
120
|
+
return (await running).exitCode;
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
process.stderr.write((error instanceof Error ? error.message : "主控连接失败") + "\n");
|
|
124
|
+
return 1;
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
closed = true;
|
|
128
|
+
socket.destroy();
|
|
129
|
+
process.removeListener("SIGINT", interrupt);
|
|
130
|
+
process.removeListener("SIGTERM", terminate);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { AgentEventEnvelope, TurnExecutionView } from "@autopilot-agent/core";
|
|
2
|
+
import { type CliController } from "./controller.js";
|
|
3
|
+
import type { CliProjection } from "./types.js";
|
|
4
|
+
export interface ManagedCliSnapshot {
|
|
5
|
+
sessionId?: string;
|
|
6
|
+
runId?: string;
|
|
7
|
+
workspaceRoot?: string;
|
|
8
|
+
status: string;
|
|
9
|
+
cancelToken?: string;
|
|
10
|
+
checkoutNotice?: string;
|
|
11
|
+
task?: {
|
|
12
|
+
id: string;
|
|
13
|
+
content: string;
|
|
14
|
+
};
|
|
15
|
+
receiptNotice?: string;
|
|
16
|
+
approvalStatus?: string;
|
|
17
|
+
queueStarts?: {
|
|
18
|
+
inputId: string;
|
|
19
|
+
turnId: string;
|
|
20
|
+
}[];
|
|
21
|
+
queueRejections?: {
|
|
22
|
+
inputId: string;
|
|
23
|
+
message: string;
|
|
24
|
+
}[];
|
|
25
|
+
inspection?: {
|
|
26
|
+
turnId?: string;
|
|
27
|
+
status: string;
|
|
28
|
+
execution: string;
|
|
29
|
+
recoverable: boolean;
|
|
30
|
+
interaction?: {
|
|
31
|
+
state: string;
|
|
32
|
+
question?: NonNullable<TurnExecutionView["interaction"]>["question"];
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
pendingApproval?: {
|
|
36
|
+
turnId: string;
|
|
37
|
+
approval: NonNullable<CliProjection["pendingApproval"]>;
|
|
38
|
+
};
|
|
39
|
+
page?: {
|
|
40
|
+
items: AgentEventEnvelope[];
|
|
41
|
+
cursor?: string;
|
|
42
|
+
nextCursor?: string;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export type ManagedCliRequest = (operation: "read" | "input" | "cli" | "cancel" | "ready", extra?: Record<string, unknown>) => Promise<unknown>;
|
|
46
|
+
/** TUI/Presentation 和问题选择沿用普通 AP;不提供创建 Runtime、切自由 Session 的能力。 */
|
|
47
|
+
export declare function createManagedCliController(request: ManagedCliRequest, notice: (text: string) => void, role?: "controller" | "executor"): CliController & {
|
|
48
|
+
update(snapshot: ManagedCliSnapshot): void;
|
|
49
|
+
};
|