@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.
Files changed (110) hide show
  1. package/README.md +15 -6
  2. package/dist/activity-animation.d.ts +5 -0
  3. package/dist/activity-animation.js +13 -17
  4. package/dist/browser-client.d.ts +14 -0
  5. package/dist/browser-client.js +156 -0
  6. package/dist/composition-root.d.ts +41 -1
  7. package/dist/composition-root.js +141 -14
  8. package/dist/context-report.d.ts +9 -4
  9. package/dist/context-report.js +15 -3
  10. package/dist/controller.d.ts +81 -4
  11. package/dist/controller.js +468 -98
  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/error-diagnostics.d.ts +2 -0
  17. package/dist/error-diagnostics.js +3 -1
  18. package/dist/event-projector.d.ts +16 -2
  19. package/dist/event-projector.js +74 -5
  20. package/dist/file-mention-budget.d.ts +16 -0
  21. package/dist/file-mention-budget.js +82 -0
  22. package/dist/file-mention-context.d.ts +26 -1
  23. package/dist/file-mention-context.js +70 -22
  24. package/dist/index.d.ts +1 -1
  25. package/dist/main.d.ts +3 -0
  26. package/dist/main.js +213 -12
  27. package/dist/managed-attach.d.ts +3 -0
  28. package/dist/managed-attach.js +132 -0
  29. package/dist/managed-controller.d.ts +49 -0
  30. package/dist/managed-controller.js +171 -0
  31. package/dist/orchestration-templates.d.ts +27 -0
  32. package/dist/orchestration-templates.js +20 -0
  33. package/dist/parser.d.ts +1 -1
  34. package/dist/parser.js +510 -2
  35. package/dist/renderer.js +3 -1
  36. package/dist/session-summary.d.ts +7 -0
  37. package/dist/session-summary.js +25 -0
  38. package/dist/session-title.d.ts +5 -0
  39. package/dist/session-title.js +10 -0
  40. package/dist/thread-commands.d.ts +37 -0
  41. package/dist/thread-commands.js +233 -0
  42. package/dist/thread-host.d.ts +36 -0
  43. package/dist/thread-host.js +79 -0
  44. package/dist/timeline-lines.js +36 -28
  45. package/dist/tui/app.d.ts +22 -0
  46. package/dist/tui/app.js +179 -43
  47. package/dist/tui/approval.d.ts +4 -0
  48. package/dist/tui/approval.js +13 -4
  49. package/dist/tui/brand/brand-header.d.ts +1 -3
  50. package/dist/tui/brand/brand-header.js +6 -8
  51. package/dist/tui/brand/logo.d.ts +3 -0
  52. package/dist/tui/brand/logo.js +89 -0
  53. package/dist/tui/brand/startup.d.ts +18 -0
  54. package/dist/tui/brand/startup.js +136 -0
  55. package/dist/tui/constants.d.ts +1 -1
  56. package/dist/tui/constants.js +1 -1
  57. package/dist/tui/context.js +1 -3
  58. package/dist/tui/desktop-resize.d.ts +9 -0
  59. package/dist/tui/desktop-resize.js +95 -0
  60. package/dist/tui/format.d.ts +1 -1
  61. package/dist/tui/format.js +19 -9
  62. package/dist/tui/hooks/use-file-mention-index.js +9 -4
  63. package/dist/tui/hooks/use-prompt-input.d.ts +54 -1
  64. package/dist/tui/hooks/use-prompt-input.js +159 -26
  65. package/dist/tui/hooks/use-status-view.d.ts +2 -2
  66. package/dist/tui/hooks/use-status-view.js +38 -11
  67. package/dist/tui/hooks/use-viewport.d.ts +2 -1
  68. package/dist/tui/hooks/use-viewport.js +15 -8
  69. package/dist/tui/inline-output.d.ts +17 -0
  70. package/dist/tui/inline-output.js +31 -0
  71. package/dist/tui/input/clipboard-image.d.ts +17 -0
  72. package/dist/tui/input/clipboard-image.js +117 -0
  73. package/dist/tui/input-area.d.ts +12 -1
  74. package/dist/tui/input-area.js +28 -8
  75. package/dist/tui/lifecycle.d.ts +1 -1
  76. package/dist/tui/lifecycle.js +84 -16
  77. package/dist/tui/markdown/diff.d.ts +1 -1
  78. package/dist/tui/markdown/diff.js +28 -1
  79. package/dist/tui/performance-diagnostics.js +2 -0
  80. package/dist/tui/pickers/permission.js +1 -1
  81. package/dist/tui/pickers/slash.d.ts +11 -2
  82. package/dist/tui/pickers/slash.js +21 -7
  83. package/dist/tui/prompt-input.d.ts +2 -0
  84. package/dist/tui/prompt-input.js +6 -4
  85. package/dist/tui/render-mode.d.ts +8 -4
  86. package/dist/tui/render-mode.js +17 -11
  87. package/dist/tui/run.js +53 -55
  88. package/dist/tui/session-manager.d.ts +116 -0
  89. package/dist/tui/session-manager.js +384 -0
  90. package/dist/tui/session-workspace.d.ts +9 -0
  91. package/dist/tui/session-workspace.js +383 -0
  92. package/dist/tui/status-line.d.ts +4 -0
  93. package/dist/tui/status-line.js +34 -13
  94. package/dist/tui/store.d.ts +3 -1
  95. package/dist/tui/store.js +60 -14
  96. package/dist/tui/timeline/live.js +2 -3
  97. package/dist/tui/timeline/progress.js +3 -2
  98. package/dist/tui/timeline/static-timeline.js +1 -2
  99. package/dist/tui/timeline/turn.js +3 -2
  100. package/dist/tui/transcript.d.ts +2 -1
  101. package/dist/tui/transcript.js +43 -5
  102. package/dist/tui/trust-dialog.d.ts +3 -0
  103. package/dist/tui/trust-dialog.js +23 -2
  104. package/dist/tui/types.d.ts +18 -1
  105. package/dist/tui/types.js +4 -1
  106. package/dist/tui/viewport/selection.d.ts +2 -2
  107. package/dist/tui/viewport/selection.js +13 -6
  108. package/dist/tui/viewport/sources.js +13 -14
  109. package/dist/types.d.ts +160 -3
  110. package/package.json +4 -4
@@ -1,4 +1,3 @@
1
- /** CLI TUI 语义色 token;组件只引用 token,不直接写危险态颜色。 */
2
1
  export declare const CLI_TUI_COLORS: {
3
2
  readonly accent: "ansi256(208)";
4
3
  readonly permissionFullAccess: "#ff6b80";
@@ -12,6 +11,10 @@ export declare const CLI_TUI_COLORS: {
12
11
  };
13
12
  /** Design.md 中橙色强调色的 ANSI 256 语义映射;NO_COLOR 时完全不输出颜色。 */
14
13
  export declare const TUI_ACCENT_COLOR: "ansi256(208)";
14
+ /** 编排受管终端的模型名使用同一个强调色,不修改 Ink 的全局颜色级别。 */
15
+ export declare const TUI_MANAGED_MODEL_ACCENT_SGR = "\u001B[38;5;208m";
16
+ /** 受管终端的风险标签沿用普通 TUI 的完全访问红色。 */
17
+ export declare const TUI_MANAGED_FULL_ACCESS_SGR: string;
15
18
  /** 工具徽标 chip 的强调背景色;与唯一强调色同源,只用于标注当前活动步骤。 */
16
19
  export declare const TUI_ACCENT_BG_COLOR: "ansi256(208)";
17
20
  /** 工具徽标 chip 上的深色粗体文字色;对应 Web 的 text-ink-on-dark 槽位语义。 */
@@ -34,5 +37,7 @@ export declare const TUI_WAITING_BACKGROUND_COLOR = "ansi256(236)";
34
37
  export declare const TUI_DIFF_ADDED_COLOR = "ansi256(46)";
35
38
  /** unified diff 删除行的语义色。 */
36
39
  export declare const TUI_DIFF_REMOVED_COLOR = "ansi256(196)";
37
- /** 输入区(prompt)的背景色。 */
40
+ /** 用户提示词背景,与 Desktop 深灰侧栏接近。 */
38
41
  export declare const TUI_PROMPT_BACKGROUND_COLOR = "ansi256(236)";
42
+ /** 编排主控仅为已提交消息绘制此背景,不修改 Ink 的全局颜色级别。 */
43
+ export declare const TUI_MANAGED_PROMPT_BACKGROUND_SGR = "\u001B[48;5;236m";
@@ -1,6 +1,7 @@
1
1
  /** CLI TUI 语义色 token;组件只引用 token,不直接写危险态颜色。 */
2
+ const tuiAccentIndex = 208;
2
3
  export const CLI_TUI_COLORS = {
3
- accent: "ansi256(208)",
4
+ accent: `ansi256(${tuiAccentIndex})`,
4
5
  permissionFullAccess: "#ff6b80",
5
6
  copilotBlue: "ansi256(33)",
6
7
  copilotBlueBright: "ansi256(39)",
@@ -12,6 +13,10 @@ export const CLI_TUI_COLORS = {
12
13
  };
13
14
  /** Design.md 中橙色强调色的 ANSI 256 语义映射;NO_COLOR 时完全不输出颜色。 */
14
15
  export const TUI_ACCENT_COLOR = CLI_TUI_COLORS.accent;
16
+ /** 编排受管终端的模型名使用同一个强调色,不修改 Ink 的全局颜色级别。 */
17
+ export const TUI_MANAGED_MODEL_ACCENT_SGR = `\u001b[38;5;${tuiAccentIndex}m`;
18
+ /** 受管终端的风险标签沿用普通 TUI 的完全访问红色。 */
19
+ export const TUI_MANAGED_FULL_ACCESS_SGR = `\u001b[38;2;${CLI_TUI_COLORS.permissionFullAccess.slice(1).match(/../g).map(function component(value) { return parseInt(value, 16); }).join(";")}m`;
15
20
  /** 工具徽标 chip 的强调背景色;与唯一强调色同源,只用于标注当前活动步骤。 */
16
21
  export const TUI_ACCENT_BG_COLOR = CLI_TUI_COLORS.accent;
17
22
  /** 工具徽标 chip 上的深色粗体文字色;对应 Web 的 text-ink-on-dark 槽位语义。 */
@@ -34,5 +39,8 @@ export const TUI_WAITING_BACKGROUND_COLOR = "ansi256(236)";
34
39
  export const TUI_DIFF_ADDED_COLOR = "ansi256(46)";
35
40
  /** unified diff 删除行的语义色。 */
36
41
  export const TUI_DIFF_REMOVED_COLOR = "ansi256(196)";
37
- /** 输入区(prompt)的背景色。 */
38
- export const TUI_PROMPT_BACKGROUND_COLOR = "ansi256(236)";
42
+ const tuiPromptBackgroundIndex = 236;
43
+ /** 用户提示词背景,与 Desktop 深灰侧栏接近。 */
44
+ export const TUI_PROMPT_BACKGROUND_COLOR = `ansi256(${tuiPromptBackgroundIndex})`;
45
+ /** 编排主控仅为已提交消息绘制此背景,不修改 Ink 的全局颜色级别。 */
46
+ export const TUI_MANAGED_PROMPT_BACKGROUND_SGR = `\u001b[48;5;${tuiPromptBackgroundIndex}m`;
@@ -0,0 +1,35 @@
1
+ import { type DesktopSessionStatus, type DesktopWorkspaceStatus } from "@autopilot-agent/adapters";
2
+ import type { Session, TurnExecutionView } from "@autopilot-agent/core";
3
+ export interface DesktopStatusSource {
4
+ workspace: DesktopWorkspaceStatus;
5
+ selected(): string;
6
+ entries(): Array<{
7
+ sessionId: string;
8
+ opened: boolean;
9
+ }>;
10
+ executions(): Array<{
11
+ threadId: string;
12
+ turnId: string;
13
+ }>;
14
+ read(sessionId: string, signal: AbortSignal): Promise<{
15
+ status?: Session["status"];
16
+ executionView?: TurnExecutionView | null;
17
+ } | null>;
18
+ recovery?(sessionId: string, turnId: string): Promise<{
19
+ sessionId: string;
20
+ turnId: string;
21
+ recoverable: boolean;
22
+ } | null>;
23
+ }
24
+ /** 明确白名单复制,Core 交互对象和错误正文永不进入通道。 */
25
+ export declare function projectDesktopSession(sessionId: string, summary: {
26
+ status?: Session["status"];
27
+ executionView?: TurnExecutionView | null;
28
+ }, relation: DesktopSessionStatus["relation"], selected: boolean): DesktopSessionStatus;
29
+ /** 缺受管环境立即返回,不分配连接或定时器。 */
30
+ export declare function createDesktopStatus(env?: NodeJS.ProcessEnv): {
31
+ bind(source: DesktopStatusSource): void;
32
+ track(sessionId: string): void;
33
+ flush(): Promise<void>;
34
+ stop(): Promise<void>;
35
+ } | undefined;
@@ -0,0 +1,304 @@
1
+ // CLI 受管状态出口,Core 只读查询决定事实,独立本机连接失败不影响任务或标准输出。
2
+ import { AUTOPILOT_VERSION } from "./tui/constants.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { createConnection } from "node:net";
5
+ import { DesktopStatusLines, DESKTOP_STATUS_FRAME_BYTES, isDesktopStatusId, isDesktopStatusReply } from "@autopilot-agent/adapters";
6
+ /** 明确白名单复制,Core 交互对象和错误正文永不进入通道。 */
7
+ export function projectDesktopSession(sessionId, summary, relation, selected) {
8
+ const view = summary.executionView;
9
+ if (!view)
10
+ return { sessionId, selected, relation, freshness: summary.status === "idle" ? "fresh" : "unknown", status: "idle", lastSeq: 0 };
11
+ return { sessionId, turnId: view.turnId, selected, relation, freshness: "fresh", status: view.status, execution: view.execution, waiting: view.waiting, result: view.result, interaction: view.interaction?.state, continuation: (view.interaction?.continuation ?? view.continuation)?.state, lastSeq: view.lastSeq };
12
+ }
13
+ /** 缺受管环境立即返回,不分配连接或定时器。 */
14
+ export function createDesktopStatus(env = process.env) {
15
+ const prefix = "AUTOPILOT_DESKTOP_STATUS_";
16
+ const endpoint = env[`${prefix}ENDPOINT`];
17
+ const token = env[`${prefix}TOKEN`];
18
+ const desktopInstanceId = env[`${prefix}INSTANCE_ID`];
19
+ const paneId = env[`${prefix}PANE_ID`];
20
+ const generation = Number(env[`${prefix}GENERATION`]);
21
+ if (!endpoint || !token || !/^[0-9a-f]{64}$/.test(token) || !isDesktopStatusId(desktopInstanceId) || !isDesktopStatusId(paneId) || !Number.isSafeInteger(generation) || generation < 1)
22
+ return undefined;
23
+ const identity = { desktopInstanceId, paneId, generation, apInstanceId: randomUUID() };
24
+ const records = new Map();
25
+ const driven = new Set();
26
+ let source;
27
+ let socket;
28
+ let stopped = false;
29
+ let reading = false;
30
+ let cursor = 0;
31
+ let seq = 0;
32
+ let retry = 100;
33
+ let reconnect;
34
+ let pending;
35
+ let sending = false;
36
+ let dirty = true;
37
+ let lastSent = "";
38
+ const abort = new AbortController();
39
+ /** 登记身份只安排查询,不把本地启动通知解释成运行或完成。 */
40
+ function track(sessionId) {
41
+ driven.add(sessionId);
42
+ const record = records.get(sessionId);
43
+ if (record)
44
+ record.generation++;
45
+ else
46
+ records.set(sessionId, { value: { sessionId, selected: false, relation: "locallyDriven", freshness: "unknown", status: "idle", lastSeq: 0 }, checked: 0, generation: 0 });
47
+ dirty = true;
48
+ }
49
+ /** 普通与退出读取共用提交边界,旧请求、错会话与落后事实不能恢复可信度。 */
50
+ function commitObservation(id, generation, value, executionSessionId) {
51
+ const record = records.get(id);
52
+ if (!record || record.generation !== generation)
53
+ return;
54
+ if (!value || executionSessionId !== undefined && executionSessionId !== id || record.value.turnId && !value.turnId || value.turnId === record.value.turnId && value.lastSeq < record.value.lastSeq)
55
+ record.value.freshness = "unknown";
56
+ else {
57
+ record.value = value;
58
+ record.checked = Date.now();
59
+ }
60
+ dirty = true;
61
+ }
62
+ /** 单连接每次只发一帧,ACK 超时直接重连,不累积发送队列。 */
63
+ async function send(payload) {
64
+ const connection = socket;
65
+ if (!connection || connection.destroyed || pending)
66
+ return false;
67
+ const frame = { ...identity, protocolVersion: 1, seq: ++seq, ...payload };
68
+ const line = JSON.stringify(frame) + "\n";
69
+ if (Buffer.byteLength(line) > DESKTOP_STATUS_FRAME_BYTES) {
70
+ connection.destroy();
71
+ return false;
72
+ }
73
+ return new Promise(function awaitAck(resolve) {
74
+ const timeout = setTimeout(function expired() { connection.destroy(); }, 2000);
75
+ timeout.unref();
76
+ pending = { seq, complete: function complete(ok) { clearTimeout(timeout); pending = undefined; resolve(ok); } };
77
+ connection.write(line);
78
+ });
79
+ }
80
+ /** 固定版本快照分批发送,发送期间的新变化合并到下一份快照。 */
81
+ async function publish() {
82
+ if (sending || stopped || !socket || pending)
83
+ return false;
84
+ sending = true;
85
+ try {
86
+ const sessions = (source ? [...records.values()] : []).map(function current(record) {
87
+ return { ...record.value, selected: source?.selected() === record.value.sessionId, freshness: Date.now() - record.checked <= 15000 ? record.value.freshness : "unknown" };
88
+ });
89
+ const content = JSON.stringify({ workspace: source?.workspace, sessions });
90
+ if (!dirty && content === lastSent)
91
+ return await send({ type: "heartbeat" });
92
+ dirty = false;
93
+ const snapshotId = randomUUID();
94
+ let part = 0;
95
+ let offset = 0;
96
+ do {
97
+ if (stopped)
98
+ return false;
99
+ const batch = [];
100
+ let bytes = 1024;
101
+ while (offset < sessions.length && batch.length < 128 && bytes + Buffer.byteLength(JSON.stringify(sessions[offset])) < DESKTOP_STATUS_FRAME_BYTES - 1024) {
102
+ const session = sessions[offset++];
103
+ batch.push(session);
104
+ bytes += Buffer.byteLength(JSON.stringify(session));
105
+ }
106
+ if (!await send({ type: "snapshot", snapshotId, part: part++, final: offset === sessions.length, lifecycle: source ? "ready" : "starting", ...(source ? { workspace: source.workspace } : {}), sessions: batch }))
107
+ return false;
108
+ } while (offset < sessions.length);
109
+ lastSent = content;
110
+ return true;
111
+ }
112
+ finally {
113
+ sending = false;
114
+ }
115
+ }
116
+ /** 有界四路查询公平推进全部目标,失败或陈旧事实显式未知。 */
117
+ async function refresh() {
118
+ if (!source || reading || stopped)
119
+ return;
120
+ reading = true;
121
+ try {
122
+ for (const execution of source.executions())
123
+ track(execution.threadId);
124
+ const opened = new Set();
125
+ for (const entry of source.entries()) {
126
+ if (entry.opened)
127
+ opened.add(entry.sessionId);
128
+ if (!records.has(entry.sessionId))
129
+ records.set(entry.sessionId, { value: { sessionId: entry.sessionId, selected: false, relation: "relatedObserved", freshness: "unknown", status: "idle", lastSeq: 0 }, checked: 0, generation: 0 });
130
+ }
131
+ const ids = [...records.keys()];
132
+ const batch = Array.from({ length: Math.min(128, ids.length) }, function fair(_, index) { return ids[(cursor + index) % ids.length]; });
133
+ cursor = ids.length ? (cursor + batch.length) % ids.length : 0;
134
+ let next = 0;
135
+ /** 每个目标最多一次读取在途,超时仅中止观察。 */
136
+ async function worker() {
137
+ while (next < batch.length && !stopped && !abort.signal.aborted) {
138
+ const id = batch[next++];
139
+ const record = records.get(id);
140
+ const generation = ++record.generation;
141
+ const observedSource = source;
142
+ const queryAbort = new AbortController();
143
+ const timeout = setTimeout(function timeoutRead() { queryAbort.abort(); }, 2000);
144
+ /** 全局退出同步终止本轮只读查询。 */
145
+ function cancelRead() { queryAbort.abort(); }
146
+ abort.signal.addEventListener("abort", cancelRead, { once: true });
147
+ try {
148
+ const summary = await observedSource.read(id, queryAbort.signal);
149
+ if (stopped || queryAbort.signal.aborted || source !== observedSource || !summary) {
150
+ commitObservation(id, generation);
151
+ continue;
152
+ }
153
+ const value = projectDesktopSession(id, summary, driven.has(id) ? "locallyDriven" : opened.has(id) ? "opened" : "relatedObserved", source.selected() === id);
154
+ if (value.turnId && value.result === "interrupted") {
155
+ if (value.turnId === record.value.turnId && value.lastSeq === record.value.lastSeq && record.value.recoverable !== undefined)
156
+ value.recoverable = record.value.recoverable;
157
+ else {
158
+ const recovery = await source.recovery?.(id, value.turnId);
159
+ if (recovery?.sessionId === id && recovery.turnId === value.turnId)
160
+ value.recoverable = recovery.recoverable;
161
+ }
162
+ }
163
+ if (stopped || queryAbort.signal.aborted || source !== observedSource) {
164
+ commitObservation(id, generation);
165
+ continue;
166
+ }
167
+ commitObservation(id, generation, value, summary.executionView?.sessionId);
168
+ }
169
+ catch {
170
+ commitObservation(id, generation);
171
+ }
172
+ finally {
173
+ clearTimeout(timeout);
174
+ abort.signal.removeEventListener("abort", cancelRead);
175
+ }
176
+ }
177
+ }
178
+ await Promise.all(Array.from({ length: Math.min(4, batch.length) }, worker));
179
+ }
180
+ finally {
181
+ reading = false;
182
+ }
183
+ }
184
+ /** 旧连接回调核对对象,重连始终从完整快照开始。 */
185
+ function connect() {
186
+ if (stopped)
187
+ return;
188
+ let connection;
189
+ try {
190
+ connection = createConnection(endpoint);
191
+ }
192
+ catch {
193
+ reconnect = setTimeout(connect, retry + Math.random() * 100);
194
+ reconnect.unref();
195
+ retry = Math.min(5000, retry * 2);
196
+ return;
197
+ }
198
+ socket = connection;
199
+ connection.unref();
200
+ const lines = new DesktopStatusLines();
201
+ connection.on("connect", function hello() { void send({ type: "hello", token, cliVersion: AUTOPILOT_VERSION }); });
202
+ connection.on("data", function receive(chunk) {
203
+ if (socket !== connection)
204
+ return;
205
+ try {
206
+ for (const value of lines.push(chunk)) {
207
+ if (!isDesktopStatusReply(value))
208
+ throw new Error("STATUS_REPLY_INVALID");
209
+ if (value.type === "resync_required") {
210
+ connection.destroy();
211
+ return;
212
+ }
213
+ if (pending?.seq !== value.seq)
214
+ continue;
215
+ pending.complete(true);
216
+ if (value.type === "accepted") {
217
+ retry = 100;
218
+ dirty = true;
219
+ void publish();
220
+ }
221
+ }
222
+ }
223
+ catch {
224
+ connection.destroy();
225
+ }
226
+ });
227
+ connection.on("error", function unavailable() { connection.destroy(); });
228
+ connection.on("close", function disconnected() {
229
+ if (socket !== connection)
230
+ return;
231
+ socket = undefined;
232
+ pending?.complete(false);
233
+ if (!stopped) {
234
+ reconnect = setTimeout(connect, retry + Math.random() * 100);
235
+ reconnect.unref();
236
+ retry = Math.min(5000, retry * 2);
237
+ }
238
+ });
239
+ }
240
+ const timer = setInterval(function update() { void refresh(); void publish(); }, 1000);
241
+ timer.unref();
242
+ connect();
243
+ return {
244
+ bind: function bind(value) { for (const record of records.values())
245
+ record.generation++; source = value; track(value.selected()); void refresh(); },
246
+ track,
247
+ flush: async function flush() {
248
+ clearInterval(timer);
249
+ abort.abort();
250
+ if (!source || stopped)
251
+ return;
252
+ const observedSource = source;
253
+ const id = observedSource.selected();
254
+ const record = records.get(id) ?? { value: { sessionId: id, selected: true, relation: "opened", freshness: "unknown", status: "idle", lastSeq: 0 }, checked: 0, generation: 0 };
255
+ records.set(id, record);
256
+ const generation = ++record.generation;
257
+ commitObservation(id, generation);
258
+ const controller = new AbortController();
259
+ let timeout;
260
+ try {
261
+ const read = observedSource.read(id, controller.signal);
262
+ const summary = await Promise.race([read, new Promise(function deadline(resolve) { timeout = setTimeout(function expired() { controller.abort(); resolve(null); }, 500); })]);
263
+ if (summary && !controller.signal.aborted && source === observedSource && observedSource.selected() === id) {
264
+ const value = projectDesktopSession(id, summary, driven.has(id) ? "locallyDriven" : "opened", true);
265
+ const previous = records.get(id)?.value;
266
+ if (previous?.turnId === value.turnId && previous?.lastSeq === value.lastSeq)
267
+ value.recoverable = previous?.recoverable;
268
+ commitObservation(id, generation, value, summary.executionView?.sessionId);
269
+ }
270
+ }
271
+ catch {
272
+ commitObservation(id, generation);
273
+ }
274
+ finally {
275
+ clearTimeout(timeout);
276
+ }
277
+ const deadline = Date.now() + 250;
278
+ while ((sending || pending) && Date.now() < deadline)
279
+ await new Promise(function delay(resolve) { setTimeout(resolve, 10); });
280
+ const published = await Promise.race([publish(), new Promise(function bounded(resolve) { setTimeout(function expired() { resolve(false); }, Math.max(0, deadline - Date.now())); })]);
281
+ // 最终降级事实未完整送达时保留断线,不让退出通知恢复旧摘要的可信度。
282
+ if (!published || source !== observedSource || observedSource.selected() !== id || record.generation !== generation)
283
+ socket?.destroy();
284
+ },
285
+ stop: async function stop() {
286
+ if (stopped)
287
+ return;
288
+ stopped = true;
289
+ clearInterval(timer);
290
+ clearTimeout(reconnect);
291
+ abort.abort();
292
+ // 退出只有限等待在途状态帧,原业务停机结果已由 Core 持久化。
293
+ const deadline = Date.now() + 250;
294
+ while (pending && Date.now() < deadline)
295
+ await new Promise(function delay(resolve) { setTimeout(resolve, 10); });
296
+ if (!pending) {
297
+ const flush = send({ type: "ap_exiting" });
298
+ await Promise.race([flush, new Promise(function limit(resolve) { setTimeout(resolve, 100); })]);
299
+ }
300
+ socket?.destroy();
301
+ pending?.complete(false);
302
+ },
303
+ };
304
+ }
@@ -1,4 +1,6 @@
1
1
  /** CLI 内部错误的安全分类:只返回封闭类别与稳定错误码,不读取异常正文。 */
2
+ /** 旧缺省归属的人类恢复说明,复用只读发现与精确CAS命令。 */
3
+ export declare const CLI_THREAD_RECOVERY_HINT = "\u6267\u884C\u5F52\u5C5E\u5F85\u786E\u8BA4\u3002\u7528 ap session list \u53D6\u5F97\u4F1A\u8BDDid\uFF0C\u518D\u7528 ap thread group of --thread <id> \u8BFB\u53D6groupId/revision\uFF0Cap thread list --group <groupId> \u67E5\u770B\u76EE\u6807\u3002\u5BF9\u65E0\u6267\u884C\u4E8B\u5B9E\u6216\u5DF2\u786E\u8BA4completed\u7684\u65E7\u76EE\u6807\uFF0C\u7528 ap thread bind-host --group <groupId> --thread <id> --expected-revision <revision> --execution-host <cli-work-v1|web-work-v1> \u9009\u62E9\u540E\u5F00\u59CB\u65B0\u4EFB\u52A1\uFF1B\u7B49\u5F85/\u4E2D\u65AD/\u7ED3\u679C\u672A\u786E\u8BA4\u7684\u539F\u4EFB\u52A1\u5E94\u5728\u517C\u5BB9\u5BBF\u4E3B\u5904\u7406";
2
4
  export type CliErrorCategory = "config_directory" | "workspace_trust" | "agent_runtime" | "node_state" | "node_chat" | "unknown";
3
5
  export interface CliErrorClassification {
4
6
  category: CliErrorCategory;
@@ -1,6 +1,8 @@
1
1
  /** CLI 内部错误的安全分类:只返回封闭类别与稳定错误码,不读取异常正文。 */
2
2
  import { NodeChatError, NodeStateError } from "@autopilot-agent/adapters";
3
3
  import { AgentRuntimeError, WorkspaceTrustError } from "@autopilot-agent/core";
4
+ /** 旧缺省归属的人类恢复说明,复用只读发现与精确CAS命令。 */
5
+ export const CLI_THREAD_RECOVERY_HINT = "执行归属待确认。用 ap session list 取得会话id,再用 ap thread group of --thread <id> 读取groupId/revision,ap thread list --group <groupId> 查看目标。对无执行事实或已确认completed的旧目标,用 ap thread bind-host --group <groupId> --thread <id> --expected-revision <revision> --execution-host <cli-work-v1|web-work-v1> 选择后开始新任务;等待/中断/结果未确认的原任务应在兼容宿主处理";
4
6
  const agentErrorCodes = new Set([
5
7
  "SESSION_MODE_MISMATCH", "CHAT_RETRIEVAL_MODE_LOCKED", "CHAT_TOOL_FORBIDDEN", "CHAT_RAG_EVIDENCE_INSUFFICIENT",
6
8
  "WORKSPACE_REQUIRED", "WORK_HISTORY_READ_ONLY", "SESSION_NOT_FOUND", "SESSION_TITLE_INVALID", "TURN_NOT_FOUND",
@@ -13,7 +15,7 @@ const agentErrorCodes = new Set([
13
15
  "JOB_NOT_FOUND", "JOB_INPUT_INVALID", "JOB_CURSOR_INVALID", "JOB_OWNER_UNAVAILABLE", "JOB_OWNER_UNKNOWN",
14
16
  "JOB_STATE_CONFLICT", "JOB_STOP_TIMEOUT", "JOB_STOP_FAILED", "JOB_STORAGE_FAILED", "JOB_SPAWN_FAILED",
15
17
  "JOB_STORE_CAPABILITY_UNSUPPORTED", "SESSION_HAS_ACTIVE_JOBS", "INTERACTIVE_TOOL_CONFLICT", "INBOX_INPUT_NOT_FOUND",
16
- "INVALID_INPUT",
18
+ "INVALID_INPUT", "THREAD_RECOVERY_REQUIRED",
17
19
  ]);
18
20
  const nodeStateErrorCodes = new Set([
19
21
  "STATE_SESSION_CORRUPTED", "STATE_STORAGE_UNAVAILABLE", "STATE_STORAGE_UNSAFE_PATH", "STATE_SCHEMA_UNSAFE_PATH",
@@ -4,8 +4,8 @@
4
4
  * 它在宿主边界补充本地 seq,并把 Core 事件归约为不包含 checkpoint、冻结
5
5
  * 工具输入、raw reasoning 或绝对受控路径的公开 ViewModel。
6
6
  */
7
- import { type AgentEvent, type RecoverableTurnView } from "@autopilot-agent/core";
8
- import type { CliEventEnvelope, CliProjection } from "./types.js";
7
+ import { type AgentEvent, type AgentEventEnvelope, type RecoverableTurnView } from "@autopilot-agent/core";
8
+ import type { CliEventEnvelope, CliProjection, CliTurnStatus } from "./types.js";
9
9
  /** 创建空的 CLI 投影状态。 */
10
10
  export declare function createInitialCliProjection(): CliProjection;
11
11
  /** 归约单个本地事件信封;同一 turn/seq 重复信封不会再次产生公开事件。 */
@@ -20,7 +20,21 @@ export declare function createCliEventProjector(options?: {
20
20
  projection: CliProjection;
21
21
  added: boolean;
22
22
  };
23
+ observe(envelope: AgentEventEnvelope): {
24
+ projection: CliProjection;
25
+ added: boolean;
26
+ };
23
27
  getProjection(): CliProjection;
28
+ invalidateObservedTurn(input: {
29
+ turnId?: string;
30
+ status: CliTurnStatus;
31
+ }): CliProjection;
32
+ syncObservedInteraction(input: {
33
+ turnId: string;
34
+ status: CliTurnStatus;
35
+ approval?: AgentEventEnvelope;
36
+ requestId?: string;
37
+ }): CliProjection;
24
38
  setSessionId(sessionId: string): void;
25
39
  restore(view: RecoverableTurnView): CliProjection;
26
40
  };
@@ -4,8 +4,8 @@
4
4
  * 它在宿主边界补充本地 seq,并把 Core 事件归约为不包含 checkpoint、冻结
5
5
  * 工具输入、raw reasoning 或绝对受控路径的公开 ViewModel。
6
6
  */
7
- import { sanitizeAgentTerminationView } from "@autopilot-agent/core";
8
- import { createPresentationState, getPresentationCopy, getToolPresentationProfile, reducePresentationInput } from "@autopilot-agent/presentation";
7
+ import { getAgentProviderFailureMessage, sanitizeAgentProviderFailureDetail, normalizeLegacyProviderFailureReason, sanitizeAgentTerminationView } from "@autopilot-agent/core";
8
+ import { createPresentationState, getPresentationCopy, getToolPresentationProfile, reconcilePresentationApprovals, reducePresentationInput } from "@autopilot-agent/presentation";
9
9
  /** 创建空的 CLI 投影状态。 */
10
10
  export function createInitialCliProjection() {
11
11
  return {
@@ -55,10 +55,18 @@ function safeErrorCode(value) {
55
55
  "TOOL_CALL_INVALID_JSON",
56
56
  "TOOL_CALL_TRUNCATED",
57
57
  "PROVIDER_UNAUTHORIZED",
58
+ "PROVIDER_CONNECTION",
59
+ "PROVIDER_TIMEOUT",
60
+ "PROVIDER_RATE_LIMIT",
61
+ "PROVIDER_SERVER_ERROR",
62
+ "PROVIDER_REQUEST_REJECTED",
58
63
  "MODEL_NOT_FOUND",
59
64
  "RUNTIME_ERROR",
60
65
  "COMMAND_FAILED",
61
66
  "TOOL_TIMEOUT",
67
+ "IMAGE_VISION_UNAVAILABLE",
68
+ "IMAGE_VISION_FAILED",
69
+ "IMAGE_INPUT_UNAVAILABLE",
62
70
  ];
63
71
  return knownCodes.find(function findKnownCode(code) { return text.includes(code); });
64
72
  }
@@ -78,10 +86,18 @@ function safeTurnFailureReason(value) {
78
86
  "模型输出连续截断,已达到最大恢复次数",
79
87
  "上下文溢出后已完成一次压缩重试,compact 熔断器已阻止重复请求",
80
88
  "reactive compact 失败,已熔断以避免重复请求",
89
+ "视觉分析工具不可用,无法处理图片",
90
+ "图片视觉分析失败,无法继续处理",
91
+ "会话图片不可用或已损坏",
81
92
  "Agent Loop 执行失败",
82
93
  ];
83
94
  return safeReasons.find(function matchSafeReason(reason) { return text === reason; });
84
95
  }
96
+ /** 只接受 Core Recorder 生成的 UUID 形状,避免任意失败字段进入 CLI 输出。 */
97
+ function safeFeedbackId(value) {
98
+ const text = String(value ?? "");
99
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(text) ? text : undefined;
100
+ }
85
101
  /** 复制投影状态,确保 reducer 不修改调用方持有的旧快照。 */
86
102
  function cloneProjection(previous, envelope) {
87
103
  const seenKeys = new Set(previous.seenKeys);
@@ -105,8 +121,12 @@ function sameSkills(first, second) {
105
121
  /** 从 checkpoint 提取只包含 Skill 身份的安全投影。 */
106
122
  function applyCheckpoint(projection, checkpoint, seq, turnId) {
107
123
  projection.status = mapCheckpointStatus(checkpoint.status);
124
+ if (checkpoint.status !== "running")
125
+ projection.threadWait = undefined;
108
126
  if (checkpoint.status !== "awaiting_approval")
109
127
  projection.pendingApproval = undefined;
128
+ if (checkpoint.status !== "awaiting_user_input")
129
+ projection.questionRequestId = undefined;
110
130
  const activeSkills = (checkpoint.activeSkills ?? []).map(function copySkill(skill) {
111
131
  return { skillId: skill.skillId, contentHash: skill.contentHash };
112
132
  });
@@ -126,8 +146,14 @@ function projectEvent(envelope, projection) {
126
146
  switch (event.type) {
127
147
  case "turn_started":
128
148
  projection.status = "running";
149
+ projection.pendingApproval = undefined;
150
+ projection.questionRequestId = undefined;
151
+ projection.threadWait = undefined;
129
152
  projection.recoverable = false;
130
153
  return { ...base, type: "turn_started", stepCount: event.stepCount };
154
+ case "thread_wait":
155
+ projection.threadWait = event.phase === "none" ? undefined : { phase: event.phase, pending: event.pending, running: event.running, approvals: event.approvals };
156
+ return { ...base, ...projection.threadWait, type: "thread_wait", phase: event.phase, pending: event.pending, running: event.running, approvals: event.approvals };
131
157
  case "reasoning_summary":
132
158
  return { ...base, type: "reasoning_summary", summary: sanitizeText(event.summary) };
133
159
  case "reasoning_delta":
@@ -143,6 +169,7 @@ function projectEvent(envelope, projection) {
143
169
  projection.answer = "";
144
170
  return { ...base, type: "answer_reset" };
145
171
  case "tool_started":
172
+ projection.threadWait = undefined;
146
173
  {
147
174
  const profile = getToolPresentationProfile(event.toolName);
148
175
  return {
@@ -204,6 +231,10 @@ function projectEvent(envelope, projection) {
204
231
  display,
205
232
  };
206
233
  }
234
+ case "question_required":
235
+ projection.questionRequestId = event.requestId;
236
+ projection.status = "waiting_user_input";
237
+ return undefined;
207
238
  case "input_queued":
208
239
  return { ...base, type: "input_queued", inputId: event.inputId, delivery: event.delivery };
209
240
  case "todo_updated":
@@ -249,12 +280,26 @@ function projectEvent(envelope, projection) {
249
280
  if (event.type === "turn_failed") {
250
281
  const failedStatus = projection.status === "idle" ? "failed" : projection.status;
251
282
  const termination = sanitizeAgentTerminationView(event.termination);
283
+ const code = safeErrorCode(event.errorCode) ?? safeErrorCode(event.error) ?? "RUNTIME_ERROR";
284
+ const providerHttpStatus = code.startsWith("PROVIDER_")
285
+ && Number.isInteger(event.providerHttpStatus)
286
+ && event.providerHttpStatus >= 400
287
+ && event.providerHttpStatus <= 599
288
+ ? event.providerHttpStatus
289
+ : undefined;
290
+ const providerFailureDetail = code.startsWith("PROVIDER_") ? sanitizeAgentProviderFailureDetail(event.providerFailureDetail) : undefined;
291
+ const feedbackId = safeFeedbackId(event.feedbackId);
292
+ const legacyProfile = event.providerFailureProfile;
293
+ const providerFailureReason = getAgentProviderFailureMessage(code, event.providerFailureReason ?? normalizeLegacyProviderFailureReason(code, legacyProfile, providerHttpStatus));
252
294
  return {
253
295
  ...base,
254
296
  type: "status",
255
297
  status: failedStatus,
256
- code: safeErrorCode(event.error) ?? "RUNTIME_ERROR",
257
- reason: termination?.reason ? undefined : safeTurnFailureReason(event.error),
298
+ code,
299
+ reason: providerFailureReason ?? (termination?.reason ? undefined : safeTurnFailureReason(event.error)),
300
+ ...(feedbackId ? { feedbackId } : {}),
301
+ ...(providerHttpStatus !== undefined ? { providerHttpStatus } : {}),
302
+ ...(providerFailureDetail ? { providerFailureDetail } : {}),
258
303
  ...(termination ? { termination } : {}),
259
304
  };
260
305
  }
@@ -305,15 +350,39 @@ export function createCliEventProjector(options = {}) {
305
350
  projection = reduceCliEvent(projection, envelope);
306
351
  return { envelope, projection, added: projection.events.length > previousLength };
307
352
  },
353
+ /** 持久事件按真实 Session/Turn/seq 去重,不生成新的本地身份或执行副作用。 */
354
+ observe(envelope) {
355
+ if (envelope.sessionId !== sessionId || envelope.seq <= (nextSeqByTurn.get(envelope.turnId) ?? 0))
356
+ return { projection, added: false };
357
+ nextSeqByTurn.set(envelope.turnId, Math.max(nextSeqByTurn.get(envelope.turnId) ?? 0, envelope.seq));
358
+ const previousLength = projection.events.length;
359
+ projection = reduceCliEvent(projection, envelope);
360
+ return { projection, added: projection.events.length > previousLength };
361
+ },
308
362
  getProjection() {
309
363
  return projection;
310
364
  },
365
+ /** 权威身份改变时清除旧审批/问答投影,不伪造事件或恢复凭证。 */
366
+ invalidateObservedTurn(input) {
367
+ projection = { ...createInitialCliProjection(), turnId: input.turnId, status: input.status };
368
+ return projection;
369
+ },
370
+ /** 当前交互来自独立安全摘要,不推进正文游标或seenKeys,避免跨页审批吞掉历史正文。 */
371
+ syncObservedInteraction(input) {
372
+ const envelope = input.approval;
373
+ const valid = input.status === "waiting_approval" && envelope !== undefined && envelope.sessionId === sessionId && envelope.turnId === input.turnId && envelope.event.type === "approval_required";
374
+ const interaction = valid ? reduceCliEvent(createInitialCliProjection(), envelope) : undefined;
375
+ projection = { ...projection, questionRequestId: input.status === "waiting_user_input" ? input.requestId ?? (projection.turnId === input.turnId ? projection.questionRequestId : undefined) : undefined, turnId: input.turnId, status: input.status, pendingApproval: interaction?.pendingApproval };
376
+ return projection;
377
+ },
311
378
  setSessionId(nextSessionId) {
312
379
  sessionId = nextSessionId;
313
380
  },
314
381
  restore(view) {
315
382
  const restored = createInitialCliProjection();
316
383
  restored.turnId = view.turnId;
384
+ if (projection.turnId === view.turnId)
385
+ restored.presentation = reconcilePresentationApprovals(projection.presentation, view.approval?.approvalId);
317
386
  restored.lastSeq = view.lastSeq;
318
387
  restored.status = view.status === "awaiting_approval"
319
388
  ? "waiting_approval"
@@ -325,7 +394,7 @@ export function createCliEventProjector(options = {}) {
325
394
  restored.events.push({ type: "status", seq: view.lastSeq ?? 0, turnId: view.turnId, status: restored.status, termination: sanitizeAgentTerminationView(view.termination) });
326
395
  }
327
396
  restored.activeSkills = view.activeSkills.map(function copySkill(skill) { return { ...skill }; });
328
- if (view.approval)
397
+ if (view.approval && (!view.interactionState || view.interactionState === "pending"))
329
398
  restored.pendingApproval = { ...view.approval };
330
399
  projection = restored;
331
400
  nextSeqByTurn.set(view.turnId, view.lastSeq ?? 0);
@@ -0,0 +1,16 @@
1
+ /** CLI 共用的 @ 文件预算,始终先为已核验的路径预留空间。 */
2
+ /** 摘录省略时只提供路径,截断标记随引用传递给模型。 */
3
+ export interface FileMentionReference {
4
+ path: string;
5
+ label?: string;
6
+ excerpt?: string;
7
+ truncated?: true;
8
+ }
9
+ type FileMentionGroups = readonly (readonly FileMentionReference[] | undefined)[];
10
+ /** 生成普通 CLI 的模型输入,也是两种交互入口计算共同预算的格式。 */
11
+ export declare function formatFileMentionContent(content: string, sections?: readonly FileMentionReference[]): string;
12
+ /** 对原文和引用应用共同软预算,原文始终保留。 */
13
+ export declare function fitFileMentionContext(content: string, sections?: readonly FileMentionReference[]): readonly FileMentionReference[] | undefined;
14
+ /** 先装入各组路径,再按顺序给摘录分配剩余空间,预算由实际输出格式计算。 */
15
+ export declare function fitFileMentionReferences(groups: FileMentionGroups, fits: (references: FileMentionGroups) => boolean): FileMentionGroups;
16
+ export {};