@autopilot-agent/cli 0.3.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.
Files changed (75) hide show
  1. package/README.md +8 -4
  2. package/dist/activity-animation.d.ts +1 -0
  3. package/dist/activity-animation.js +4 -2
  4. package/dist/browser-client.d.ts +14 -0
  5. package/dist/browser-client.js +156 -0
  6. package/dist/composition-root.d.ts +12 -2
  7. package/dist/composition-root.js +33 -15
  8. package/dist/context-report.d.ts +1 -1
  9. package/dist/context-report.js +1 -1
  10. package/dist/controller.d.ts +48 -1
  11. package/dist/controller.js +50 -24
  12. package/dist/design-tokens.d.ts +7 -2
  13. package/dist/design-tokens.js +11 -3
  14. package/dist/desktop-status.d.ts +35 -0
  15. package/dist/desktop-status.js +304 -0
  16. package/dist/file-mention-budget.d.ts +16 -0
  17. package/dist/file-mention-budget.js +82 -0
  18. package/dist/file-mention-context.d.ts +26 -1
  19. package/dist/file-mention-context.js +70 -22
  20. package/dist/main.d.ts +3 -0
  21. package/dist/main.js +76 -10
  22. package/dist/managed-attach.d.ts +3 -0
  23. package/dist/managed-attach.js +132 -0
  24. package/dist/managed-controller.d.ts +49 -0
  25. package/dist/managed-controller.js +171 -0
  26. package/dist/orchestration-templates.d.ts +27 -0
  27. package/dist/orchestration-templates.js +20 -0
  28. package/dist/parser.d.ts +1 -1
  29. package/dist/parser.js +14 -4
  30. package/dist/thread-host.d.ts +5 -0
  31. package/dist/thread-host.js +3 -0
  32. package/dist/tui/app.js +82 -18
  33. package/dist/tui/approval.js +1 -1
  34. package/dist/tui/brand/brand-header.d.ts +1 -3
  35. package/dist/tui/brand/brand-header.js +6 -8
  36. package/dist/tui/brand/logo.d.ts +3 -0
  37. package/dist/tui/brand/logo.js +89 -0
  38. package/dist/tui/brand/startup.d.ts +18 -0
  39. package/dist/tui/brand/startup.js +136 -0
  40. package/dist/tui/constants.d.ts +1 -1
  41. package/dist/tui/constants.js +1 -1
  42. package/dist/tui/context.js +1 -3
  43. package/dist/tui/desktop-resize.d.ts +9 -0
  44. package/dist/tui/desktop-resize.js +95 -0
  45. package/dist/tui/hooks/use-file-mention-index.js +9 -4
  46. package/dist/tui/hooks/use-prompt-input.d.ts +2 -1
  47. package/dist/tui/hooks/use-prompt-input.js +12 -7
  48. package/dist/tui/hooks/use-viewport.d.ts +2 -1
  49. package/dist/tui/hooks/use-viewport.js +15 -8
  50. package/dist/tui/input-area.d.ts +4 -1
  51. package/dist/tui/input-area.js +12 -7
  52. package/dist/tui/lifecycle.d.ts +1 -1
  53. package/dist/tui/lifecycle.js +82 -11
  54. package/dist/tui/pickers/permission.js +1 -1
  55. package/dist/tui/pickers/slash.d.ts +11 -2
  56. package/dist/tui/pickers/slash.js +21 -7
  57. package/dist/tui/prompt-input.d.ts +1 -0
  58. package/dist/tui/prompt-input.js +2 -2
  59. package/dist/tui/render-mode.d.ts +4 -0
  60. package/dist/tui/render-mode.js +12 -0
  61. package/dist/tui/run.js +17 -7
  62. package/dist/tui/session-manager.d.ts +1 -0
  63. package/dist/tui/session-manager.js +1 -0
  64. package/dist/tui/status-line.d.ts +1 -0
  65. package/dist/tui/status-line.js +29 -14
  66. package/dist/tui/store.d.ts +3 -1
  67. package/dist/tui/store.js +33 -9
  68. package/dist/tui/transcript.d.ts +1 -0
  69. package/dist/tui/transcript.js +24 -4
  70. package/dist/tui/types.d.ts +10 -1
  71. package/dist/tui/viewport/selection.d.ts +2 -2
  72. package/dist/tui/viewport/selection.js +13 -6
  73. package/dist/tui/viewport/sources.js +7 -1
  74. package/dist/types.d.ts +9 -2
  75. package/package.json +4 -4
@@ -0,0 +1,82 @@
1
+ /** CLI 共用的 @ 文件预算,始终先为已核验的路径预留空间。 */
2
+ /** 交互提交的原文和文件上下文共用软预算,原文可以超出并保持原样。 */
3
+ const FILE_MENTION_CONTEXT_BYTES = 32 * 1024;
4
+ /** 生成普通 CLI 的模型输入,也是两种交互入口计算共同预算的格式。 */
5
+ export function formatFileMentionContent(content, sections) {
6
+ if (!sections?.length)
7
+ return content;
8
+ const partial = sections.some(function incomplete(section) { return section.excerpt === undefined || section.truncated === true; });
9
+ const block = [
10
+ "<system-reminder>",
11
+ partial ? "用户通过 @ 引用了以下工作区文件,缺少的内容可按路径读取,预览可直接使用路径:" : "用户通过 @ 引用了以下工作区文件,内容已直接附加:",
12
+ ...sections.map(function renderSection(section) {
13
+ if (section.excerpt === undefined)
14
+ return `--- @${section.path} (仅路径) ---`;
15
+ const label = section.truncated ? "摘录已截断" : section.label;
16
+ return `--- @${section.path} (${label}) ---\n${section.excerpt}`;
17
+ }),
18
+ "</system-reminder>",
19
+ ].join("\n");
20
+ return `${content}\n\n${block}`;
21
+ }
22
+ /** 对原文和引用应用共同软预算,原文始终保留。 */
23
+ export function fitFileMentionContext(content, sections) {
24
+ if (!sections?.length)
25
+ return undefined;
26
+ /** 普通交互按实际发送的 UTF-8 文本计算。 */
27
+ function fits([candidate]) {
28
+ return Buffer.byteLength(formatFileMentionContent(content, candidate), "utf8") <= FILE_MENTION_CONTEXT_BYTES;
29
+ }
30
+ return fits([sections]) ? sections : fitFileMentionReferences([sections], fits)[0];
31
+ }
32
+ /** 先装入各组路径,再按顺序给摘录分配剩余空间,预算由实际输出格式计算。 */
33
+ export function fitFileMentionReferences(groups, fits) {
34
+ const references = groups.map(function empty() { return undefined; });
35
+ const excerpts = [];
36
+ for (const [index, group] of groups.entries()) {
37
+ if (!group?.length)
38
+ continue;
39
+ const selected = [];
40
+ references[index] = selected;
41
+ for (const source of group) {
42
+ const reference = { path: source.path };
43
+ selected.push(reference);
44
+ if (fits(references))
45
+ excerpts.push({ reference, source });
46
+ else
47
+ selected.pop();
48
+ }
49
+ if (!selected.length)
50
+ references[index] = undefined;
51
+ }
52
+ for (const { reference, source } of excerpts) {
53
+ if (source.excerpt === undefined)
54
+ continue;
55
+ reference.excerpt = source.excerpt;
56
+ reference.label = source.label;
57
+ reference.truncated = source.truncated;
58
+ if (fits(references))
59
+ continue;
60
+ delete reference.label;
61
+ reference.truncated = true;
62
+ // 按 Unicode 码点查找能装入实际输出的最长前缀。
63
+ const characters = Array.from(source.excerpt);
64
+ let start = 0;
65
+ let end = characters.length;
66
+ while (start < end) {
67
+ const length = Math.ceil((start + end) / 2);
68
+ reference.excerpt = characters.slice(0, length).join("");
69
+ if (fits(references))
70
+ start = length;
71
+ else
72
+ end = length - 1;
73
+ }
74
+ if (start)
75
+ reference.excerpt = characters.slice(0, start).join("");
76
+ else {
77
+ delete reference.excerpt;
78
+ delete reference.truncated;
79
+ }
80
+ }
81
+ return references;
82
+ }
@@ -3,8 +3,11 @@
3
3
  * 列目录一层,把有界内容以 `<system-reminder>` 附加块按出现顺序拼回 content;
4
4
  * 失败路径(未找到/越界/过大/读取失败)降级为 notice,不阻断提交。
5
5
  */
6
+ import { type FileMentionReference } from "./file-mention-budget.js";
6
7
  /** resolveFileMentionContext 依赖的最小文件系统接缝;测试可注入受控实现。 */
7
8
  export interface FileMentionFs {
9
+ /** 返回现存路径的真实绝对路径,解析失败时抛错。 */
10
+ realpath(absolutePath: string): Promise<string>;
8
11
  /** 返回目标的存在性形态与字节大小;目标不存在时抛错。 */
9
12
  stat(absolutePath: string): Promise<{
10
13
  isFile: boolean;
@@ -26,9 +29,31 @@ export interface ResolvedFileMentionContext {
26
29
  /** 面向用户的失败提示,按 mention 出现顺序。 */
27
30
  notices: string[];
28
31
  }
32
+ /** 分开记录核验后的相对路径和摘录,供受管宿主按传输预算选用。 */
33
+ export interface FileMentionSection {
34
+ path: string;
35
+ label: string;
36
+ excerpt: string;
37
+ }
29
38
  /** 从 prompt 原文提取 @ 引用的相对路径;`@` 必须位于行首或空白后,去重保序,`\` 归一为 `/`。 */
30
39
  export declare function extractFileMentions(content: string): string[];
31
- /** 解析 prompt 中的全部 @ 引用并构造增强 content;至少一个引用成功时在原文后追加附加块。 */
40
+ /** 宿主传入已受信的真实根;拒绝随后将该路径改指其他目录的链接。 */
41
+ export declare function resolveTrustedFileMentionRoot(workspaceRoot: string, fs?: FileMentionFs): Promise<string>;
42
+ /** 解析并核验 prompt 中的 @ 引用,保留它们的出现顺序。 */
43
+ export declare function resolveFileMentionSections(content: string, workspaceRoot: string, options?: {
44
+ fs?: FileMentionFs;
45
+ }): Promise<{
46
+ sections: FileMentionSection[];
47
+ notices: string[];
48
+ }>;
49
+ /** 在共同预算内准备核验过的引用,供本地 CLI 或编排 Worker 使用。 */
50
+ export declare function prepareFileMentionContext(content: string, workspaceRoot: string, options?: {
51
+ fs?: FileMentionFs;
52
+ }): Promise<{
53
+ references: readonly FileMentionReference[] | undefined;
54
+ notices: string[];
55
+ }>;
56
+ /** 普通交互 CLI 在提交前将共同预算内的引用附加到用户原文。 */
32
57
  export declare function resolveFileMentionContext(content: string, workspaceRoot: string, options?: {
33
58
  fs?: FileMentionFs;
34
59
  }): Promise<ResolvedFileMentionContext>;
@@ -3,8 +3,9 @@
3
3
  * 列目录一层,把有界内容以 `<system-reminder>` 附加块按出现顺序拼回 content;
4
4
  * 失败路径(未找到/越界/过大/读取失败)降级为 notice,不阻断提交。
5
5
  */
6
- import { readFile as nodeReadFile, readdir as nodeReaddir, stat as nodeStat } from "node:fs/promises";
6
+ import { readFile as nodeReadFile, readdir as nodeReaddir, realpath as nodeRealpath, stat as nodeStat } from "node:fs/promises";
7
7
  import path from "node:path";
8
+ import { fitFileMentionContext, formatFileMentionContent } from "./file-mention-budget.js";
8
9
  import { FILE_MENTION_TOKEN_CHARACTER } from "./tui/input/file-mention.js";
9
10
  /** 单文件扫描上限(对齐 core read_file 的 8MiB 扫描上限),超出直接拒绝。 */
10
11
  const FILE_MENTION_SIZE_LIMIT = 8 * 1024 * 1024;
@@ -16,13 +17,17 @@ const FILE_MENTION_BYTES_LIMIT = 256 * 1024;
16
17
  const FILE_MENTION_DIRECTORY_LIMIT = 100;
17
18
  /** 默认接缝实现:直接使用 node:fs/promises。 */
18
19
  const nodeFileMentionFs = {
20
+ realpath: nodeRealpath,
21
+ /** 获取目标类型及文件大小供读取限额检查。 */
19
22
  async stat(absolutePath) {
20
23
  const stats = await nodeStat(absolutePath);
21
24
  return { isFile: stats.isFile(), isDirectory: stats.isDirectory(), size: stats.size };
22
25
  },
26
+ /** 读取已校验路径的 UTF-8 正文。 */
23
27
  readFile(absolutePath) {
24
28
  return nodeReadFile(absolutePath, "utf8");
25
29
  },
30
+ /** 枚举已校验目录的一层条目。 */
26
31
  async listDirectory(absolutePath) {
27
32
  const entries = await nodeReaddir(absolutePath, { withFileTypes: true });
28
33
  return entries.map(function toEntry(entry) {
@@ -56,6 +61,22 @@ function isInsideWorkspace(workspaceRoot, mentionPath) {
56
61
  const relative = path.relative(workspaceRoot, path.resolve(workspaceRoot, mentionPath));
57
62
  return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
58
63
  }
64
+ /** 宿主传入已受信的真实根;拒绝随后将该路径改指其他目录的链接。 */
65
+ export async function resolveTrustedFileMentionRoot(workspaceRoot, fs = nodeFileMentionFs) {
66
+ const root = await fs.realpath(workspaceRoot);
67
+ if (!path.isAbsolute(workspaceRoot) || path.relative(workspaceRoot, root) !== "")
68
+ throw new Error("FILE_MENTION_ROOT_CHANGED");
69
+ return root;
70
+ }
71
+ /** 用解析后的路径读取,发现路径在异步读取前后变动时丢弃结果。 */
72
+ async function readVerifiedTarget(fs, target, read) {
73
+ if (await fs.realpath(target) !== target)
74
+ throw new Error("FILE_MENTION_PATH_CHANGED");
75
+ const result = await read.call(fs, target);
76
+ if (await fs.realpath(target) !== target)
77
+ throw new Error("FILE_MENTION_PATH_CHANGED");
78
+ return result;
79
+ }
59
80
  /** 按 UTF-8 字节边界截断单行文本,回退扫描避免切断多字节字符。 */
60
81
  function truncateUtf8ByBytes(text, maxBytes) {
61
82
  const buffer = Buffer.from(text, "utf8");
@@ -98,12 +119,28 @@ async function resolveSingleMention(mentionPath, workspaceRoot, fs, notices) {
98
119
  return undefined;
99
120
  }
100
121
  const absolutePath = path.resolve(workspaceRoot, mentionPath);
122
+ let target;
123
+ try {
124
+ target = await fs.realpath(absolutePath);
125
+ }
126
+ catch (error) {
127
+ const code = error?.code;
128
+ notices.push(code === "ENOENT" || code === "ENOTDIR"
129
+ ? `@${mentionPath} 未找到`
130
+ : `@${mentionPath} 无法核实路径,已拒绝读取`);
131
+ return undefined;
132
+ }
133
+ const prefix = workspaceRoot.endsWith(path.sep) ? workspaceRoot : workspaceRoot + path.sep;
134
+ if (target === workspaceRoot || !target.startsWith(prefix)) {
135
+ notices.push(`@${mentionPath} 超出工作区边界,已拒绝读取`);
136
+ return undefined;
137
+ }
101
138
  let stats;
102
139
  try {
103
- stats = await fs.stat(absolutePath);
140
+ stats = await fs.stat(target);
104
141
  }
105
142
  catch {
106
- notices.push(`@${mentionPath} 未找到`);
143
+ notices.push(`@${mentionPath} 无法核实路径,已拒绝读取`);
107
144
  return undefined;
108
145
  }
109
146
  if (stats.isFile) {
@@ -113,22 +150,22 @@ async function resolveSingleMention(mentionPath, workspaceRoot, fs, notices) {
113
150
  }
114
151
  let text;
115
152
  try {
116
- text = await fs.readFile(absolutePath);
153
+ text = await readVerifiedTarget(fs, target, fs.readFile);
117
154
  }
118
155
  catch {
119
- notices.push(`@${mentionPath} 读取失败`);
156
+ notices.push(`@${mentionPath} 读取失败或路径无法核实`);
120
157
  return undefined;
121
158
  }
122
159
  const bounded = boundedFileText(text);
123
- return `--- @${mentionPath} (${bounded.label}) ---\n${bounded.content}`;
160
+ return { path: mentionPath, label: bounded.label, excerpt: bounded.content };
124
161
  }
125
162
  if (stats.isDirectory) {
126
163
  let entries;
127
164
  try {
128
- entries = await fs.listDirectory(absolutePath);
165
+ entries = await readVerifiedTarget(fs, target, fs.listDirectory);
129
166
  }
130
167
  catch {
131
- notices.push(`@${mentionPath} 读取失败`);
168
+ notices.push(`@${mentionPath} 读取失败或路径无法核实`);
132
169
  return undefined;
133
170
  }
134
171
  const sorted = entries.slice().sort(function compareEntries(left, right) {
@@ -143,31 +180,42 @@ async function resolveSingleMention(mentionPath, workspaceRoot, fs, notices) {
143
180
  return entry.isDirectory ? `${entry.name}/` : entry.name;
144
181
  })
145
182
  .join("\n");
146
- return `--- @${mentionPath} (${label}) ---\n${content}`;
183
+ return { path: mentionPath, label, excerpt: content };
147
184
  }
148
185
  notices.push(`@${mentionPath} 未找到`);
149
186
  return undefined;
150
187
  }
151
- /** 解析 prompt 中的全部 @ 引用并构造增强 content;至少一个引用成功时在原文后追加附加块。 */
152
- export async function resolveFileMentionContext(content, workspaceRoot, options = {}) {
188
+ /** 解析并核验 prompt 中的 @ 引用,保留它们的出现顺序。 */
189
+ export async function resolveFileMentionSections(content, workspaceRoot, options = {}) {
153
190
  const mentions = extractFileMentions(content);
154
191
  if (mentions.length === 0)
155
- return { content, notices: [] };
192
+ return { sections: [], notices: [] };
156
193
  const fs = options.fs ?? nodeFileMentionFs;
194
+ let root;
195
+ try {
196
+ root = await resolveTrustedFileMentionRoot(workspaceRoot, fs);
197
+ }
198
+ catch {
199
+ return { sections: [], notices: mentions.map(function reportUnverifiedRoot(mentionPath) {
200
+ return `@${mentionPath} 无法核实工作区,已拒绝读取`;
201
+ }) };
202
+ }
157
203
  const sections = [];
158
204
  const notices = [];
159
205
  for (const mentionPath of mentions) {
160
- const section = await resolveSingleMention(mentionPath, workspaceRoot, fs, notices);
206
+ const section = await resolveSingleMention(mentionPath, root, fs, notices);
161
207
  if (section !== undefined)
162
208
  sections.push(section);
163
209
  }
164
- if (sections.length === 0)
165
- return { content, notices };
166
- const block = [
167
- "<system-reminder>",
168
- "用户通过 @ 引用了以下工作区文件,内容已直接附加:",
169
- ...sections,
170
- "</system-reminder>",
171
- ].join("\n");
172
- return { content: `${content}\n\n${block}`, notices };
210
+ return { sections, notices };
211
+ }
212
+ /** 在共同预算内准备核验过的引用,供本地 CLI 或编排 Worker 使用。 */
213
+ export async function prepareFileMentionContext(content, workspaceRoot, options = {}) {
214
+ const { sections, notices } = await resolveFileMentionSections(content, workspaceRoot, options);
215
+ return { references: fitFileMentionContext(content, sections), notices };
216
+ }
217
+ /** 普通交互 CLI 在提交前将共同预算内的引用附加到用户原文。 */
218
+ export async function resolveFileMentionContext(content, workspaceRoot, options = {}) {
219
+ const { references, notices } = await prepareFileMentionContext(content, workspaceRoot, options);
220
+ return { content: formatFileMentionContent(content, references), notices };
173
221
  }
package/dist/main.d.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * 入口只负责 argv、Composition Root、Plain Controller 和进程生命周期的编排;
6
6
  * Session、Turn、审批、恢复和持久化规则全部委托给 Core Runtime。
7
7
  */
8
+ import { type AgentRuntime, type Project, type Session } from "@autopilot-agent/core";
8
9
  import { type CliCompositionRoot, type CreateCliCompositionRootOptions } from "./composition-root.js";
9
10
  import type { CliExitCode } from "./types.js";
10
11
  /** CLI 主入口使用的最小输出/输入流接口。 */
@@ -36,5 +37,7 @@ export interface CliMainDependencies {
36
37
  }
37
38
  /** 将宿主信号映射为固定 CLI 退出码。 */
38
39
  export declare function exitCodeForSignal(signal: "SIGINT" | "SIGTERM"): 130 | 143;
40
+ /** 读取指定 Session 或创建当前 Project 下的新 Session。 */
41
+ export declare function ensureChatSession(runtime: AgentRuntime, project: Project, sessionId: string | undefined, environment?: NodeJS.ProcessEnv): Promise<Session>;
39
42
  /** 执行 Step 5.3 CLI 入口并返回固定退出码。 */
40
43
  export declare function main(argv?: readonly string[], streams?: CliMainStreams, dependencies?: CliMainDependencies): Promise<CliExitCode>;
package/dist/main.js CHANGED
@@ -6,11 +6,14 @@
6
6
  * Session、Turn、审批、恢复和持久化规则全部委托给 Core Runtime。
7
7
  */
8
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";
9
12
  import { WEB_SEARCH_DATA_FLOW_NOTICE } from "@autopilot-agent/presentation";
10
13
  import path from "node:path";
11
14
  import fs from "node:fs";
12
15
  import readline from "node:readline";
13
- import { pathToFileURL } from "node:url";
16
+ import { fileURLToPath } from "node:url";
14
17
  import { AgentRuntimeError, ThreadServiceError, WorkspaceTrustError, } from "@autopilot-agent/core";
15
18
  import { createCliCompositionRoot } from "./composition-root.js";
16
19
  import { createCliController } from "./controller.js";
@@ -33,6 +36,9 @@ function writeControllerResult(result, streams) {
33
36
  }
34
37
  /** 将 Runtime/Trust 异常收窄为不泄露绝对路径、凭据或原始输入的诊断。 */
35
38
  function formatCliError(error) {
39
+ const browserCode = getBrowserErrorCode(error);
40
+ if (browserCode)
41
+ return browserCode;
36
42
  const classification = classifyCliError(error);
37
43
  if (classification.category === "config_directory")
38
44
  return classification.code;
@@ -166,7 +172,7 @@ async function ensureProject(runtime, workspaceRoot) {
166
172
  return runtime.projects.create({ name: path.basename(workspaceRoot) || "project", workspaceRoot });
167
173
  }
168
174
  /** 读取指定 Session 或创建当前 Project 下的新 Session。 */
169
- async function ensureChatSession(runtime, project, sessionId) {
175
+ export async function ensureChatSession(runtime, project, sessionId, environment = process.env) {
170
176
  if (sessionId) {
171
177
  const session = await runtime.sessions.get(sessionId);
172
178
  if (!session)
@@ -175,8 +181,12 @@ async function ensureChatSession(runtime, project, sessionId) {
175
181
  throw new AgentRuntimeError("INVALID_INPUT", "Session 不属于当前受信任 Project");
176
182
  return session;
177
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 启动权限无效");
178
187
  return runtime.sessions.create({
179
188
  projectId: project.id,
189
+ ...(permission ? { defaultRunConfig: { permissionMode: permission } } : {}),
180
190
  // 统一由Controller在首个有效交互时建立短标题,成功回答后沿Web范式更新。
181
191
  title: undefined,
182
192
  });
@@ -325,8 +335,24 @@ async function executeThreadInvocation(command, root, runtime, workspaceRoot, st
325
335
  }
326
336
  }
327
337
  /** 执行已经通过 parser 校验的 CLI 命令。 */
328
- async function executeInvocation(invocation, streams, dependencies) {
338
+ async function executeInvocation(invocation, streams, dependencies, desktopStatus) {
329
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
+ }
330
356
  const workspaceRoot = invocation.host.workspaceRoot ?? (command.type === "project_open" ? command.path : undefined);
331
357
  const rootFactory = dependencies.createCompositionRoot ?? createCliCompositionRoot;
332
358
  const root = rootFactory({
@@ -442,7 +468,17 @@ async function executeInvocation(invocation, streams, dependencies) {
442
468
  writeManagementResult(streams, { serverName: server.serverName, approved: false, revoked: await root.revokeMcp(trust.workspaceRoot, server.serverName) });
443
469
  return 0;
444
470
  }
445
- const runtime = await root.createRuntime(trust.workspaceRoot);
471
+ const startup = (command.type === "chat" || command.type === "resume") && command.output === "interactive" && hasTty
472
+ ? startCliStartupLogo(streams.stdout, input)
473
+ : undefined;
474
+ let runtime;
475
+ try {
476
+ runtime = await root.createRuntime(trust.workspaceRoot);
477
+ }
478
+ catch (error) {
479
+ startup?.dispose();
480
+ throw error;
481
+ }
446
482
  let threadHost;
447
483
  let sessionManager;
448
484
  try {
@@ -526,14 +562,16 @@ async function executeInvocation(invocation, streams, dependencies) {
526
562
  }
527
563
  const configurationError = root.getStartupConfigurationError?.();
528
564
  if (configurationError) {
565
+ startup?.dispose();
529
566
  streams.stderr.write(`${configurationError}\n`);
530
567
  return 1;
531
568
  }
532
569
  const project = await ensureProject(runtime, trust.workspaceRoot);
533
570
  // 协作范围按 Project 绑定;常驻宿主发现已启用组后才接管驱动,未启用时保持轻量复查。
534
571
  root.bindThreadsProject(project.id);
535
- 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); });
536
- threadHost.start();
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();
537
575
  const session = command.type === "resume"
538
576
  ? await selectResumeSession(runtime, project, command.sessionId)
539
577
  : await ensureChatSession(runtime, project, command.sessionId);
@@ -548,8 +586,23 @@ async function executeInvocation(invocation, streams, dependencies) {
548
586
  getRuntimeStatusDefaults: root.getRuntimeStatusDefaults,
549
587
  listSkills: root.listSkills,
550
588
  resolveSkill: root.resolveSkill,
551
- registerExecution: threadHost.registerExecution,
589
+ registerExecution: function registerExecution(input) { desktopStatus?.track(input.threadId); return threadHost.registerExecution(input); },
552
590
  });
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
+ });
553
606
  const recoverable = command.type === "chat" && !command.prompt && (command.output !== "interactive" || !hasTty)
554
607
  ? await runtime.turns.getRecoverableState({ sessionId: session.id })
555
608
  : undefined;
@@ -566,7 +619,7 @@ async function executeInvocation(invocation, streams, dependencies) {
566
619
  : undefined;
567
620
  sessionManager = createCliSessionManager({
568
621
  runtime, projectId: project.id, initialSession: session, initialController: controller,
569
- createController: function createForSession(sessionId) { return createCliController({ runtime, renderer, sessionId, workspaceRoot: trust.workspaceRoot, getRuntimeStatusDefaults: root.getRuntimeStatusDefaults, listSkills: root.listSkills, resolveSkill: root.resolveSkill, registerExecution: threadHost.registerExecution }); },
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); } }); },
570
623
  /** 通过既有人类只读目录查询创建/关联事实,分页不启动任何目标。 */
571
624
  readRelations: async function readRelations(sessionId, signal) {
572
625
  signal?.throwIfAborted();
@@ -597,6 +650,8 @@ async function executeInvocation(invocation, streams, dependencies) {
597
650
  readSummary: root.readSessionSummary,
598
651
  readEventPage: root.readSessionEventPage,
599
652
  });
653
+ await startup?.finish();
654
+ threadHost.start();
600
655
  sessionManager.start();
601
656
  const tuiResult = await runCliTui({
602
657
  sessionManager,
@@ -641,6 +696,7 @@ async function executeInvocation(invocation, streams, dependencies) {
641
696
  return resumed.exitCode;
642
697
  }
643
698
  finally {
699
+ startup?.dispose();
644
700
  const sessionsStopped = await sessionManager?.stop();
645
701
  const stopReport = await threadHost?.stop();
646
702
  if (sessionsStopped)
@@ -649,11 +705,16 @@ async function executeInvocation(invocation, streams, dependencies) {
649
705
  if (stopReport) {
650
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`);
651
707
  }
708
+ await desktopStatus?.flush();
652
709
  await runtime.shutdown?.();
653
710
  }
654
711
  }
655
712
  /** 执行 Step 5.3 CLI 入口并返回固定退出码。 */
656
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
+ }
657
718
  const parsed = parseArgv(argv);
658
719
  if (parsed.kind === "help") {
659
720
  streams.stdout.write(`${parsed.text}\n`);
@@ -663,15 +724,20 @@ export async function main(argv = process.argv.slice(2), streams = { stdout: pro
663
724
  streams.stderr.write(`${parsed.message}\n\n${renderHelp()}\n`);
664
725
  return 2;
665
726
  }
727
+ const desktopStatus = parsed.invocation.command.type === "chat" || parsed.invocation.command.type === "resume" ? createDesktopStatus() : undefined;
666
728
  try {
667
- return await executeInvocation(parsed.invocation, streams, dependencies);
729
+ return await executeInvocation(parsed.invocation, streams, dependencies, desktopStatus);
668
730
  }
669
731
  catch (error) {
670
732
  streams.stderr.write(`${formatCliError(error)}\n`);
671
733
  return 1;
672
734
  }
735
+ finally {
736
+ await desktopStatus?.stop();
737
+ }
673
738
  }
674
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
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])) {
675
741
  main().then(function finish(exitCode) {
676
742
  process.exitCode = exitCode;
677
743
  });
@@ -0,0 +1,3 @@
1
+ import type { CliExitCode } from "./types.js";
2
+ /** 私有能力仅用于认证;TUI和Controller不创建第二个Runtime或自由Session。 */
3
+ export declare function runManagedAttach(): Promise<CliExitCode>;
@@ -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
+ }