@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.
- package/README.md +8 -4
- package/dist/activity-animation.d.ts +1 -0
- package/dist/activity-animation.js +4 -2
- package/dist/browser-client.d.ts +14 -0
- package/dist/browser-client.js +156 -0
- package/dist/composition-root.d.ts +12 -2
- package/dist/composition-root.js +33 -15
- package/dist/context-report.d.ts +1 -1
- package/dist/context-report.js +1 -1
- package/dist/controller.d.ts +48 -1
- package/dist/controller.js +50 -24
- 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/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/main.d.ts +3 -0
- package/dist/main.js +76 -10
- 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 +14 -4
- package/dist/thread-host.d.ts +5 -0
- package/dist/thread-host.js +3 -0
- package/dist/tui/app.js +82 -18
- package/dist/tui/approval.js +1 -1
- 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/hooks/use-file-mention-index.js +9 -4
- package/dist/tui/hooks/use-prompt-input.d.ts +2 -1
- package/dist/tui/hooks/use-prompt-input.js +12 -7
- package/dist/tui/hooks/use-viewport.d.ts +2 -1
- package/dist/tui/hooks/use-viewport.js +15 -8
- package/dist/tui/input-area.d.ts +4 -1
- package/dist/tui/input-area.js +12 -7
- package/dist/tui/lifecycle.d.ts +1 -1
- package/dist/tui/lifecycle.js +82 -11
- 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 +1 -0
- package/dist/tui/prompt-input.js +2 -2
- package/dist/tui/render-mode.d.ts +4 -0
- package/dist/tui/render-mode.js +12 -0
- package/dist/tui/run.js +17 -7
- package/dist/tui/session-manager.d.ts +1 -0
- package/dist/tui/session-manager.js +1 -0
- package/dist/tui/status-line.d.ts +1 -0
- package/dist/tui/status-line.js +29 -14
- package/dist/tui/store.d.ts +3 -1
- package/dist/tui/store.js +33 -9
- package/dist/tui/transcript.d.ts +1 -0
- package/dist/tui/transcript.js +24 -4
- package/dist/tui/types.d.ts +10 -1
- package/dist/tui/viewport/selection.d.ts +2 -2
- package/dist/tui/viewport/selection.js +13 -6
- package/dist/tui/viewport/sources.js +7 -1
- package/dist/types.d.ts +9 -2
- package/package.json +4 -4
package/dist/controller.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { createCliSessionTitle, getCliSessionDisplayTitle } from "./session-title.js";
|
|
9
9
|
import { recordTuiRuntimeErrorDiagnostic } from "./tui/performance-diagnostics.js";
|
|
10
10
|
import { classifyCliError } from "./error-diagnostics.js";
|
|
11
|
+
import { prepareFileMentionContext } from "./file-mention-context.js";
|
|
11
12
|
import { randomUUID } from "node:crypto";
|
|
12
13
|
import { AgentRuntimeError, normalizeWorkImage } from "@autopilot-agent/core";
|
|
13
14
|
import { createNodeSessionImageStore } from "@autopilot-agent/adapters";
|
|
@@ -34,6 +35,24 @@ function yieldToCliRenderer() {
|
|
|
34
35
|
function isCliContinuePrompt(content) {
|
|
35
36
|
return CLI_CONTINUE_PROMPTS.has(content.trim());
|
|
36
37
|
}
|
|
38
|
+
/** 普通问题和宿主恢复问题共用编号/自定义答案解析,不将自然语言映射为隐式选择。 */
|
|
39
|
+
export function parseQuestionAnswer(content, item) {
|
|
40
|
+
const text = content.trim();
|
|
41
|
+
if (!text)
|
|
42
|
+
throw new Error("请输入当前题目的选项编号或自定义文本");
|
|
43
|
+
const custom = text.startsWith("其他 ") ? text.slice(3).trim() : undefined;
|
|
44
|
+
if (custom === "")
|
|
45
|
+
throw new Error("请输入自定义答案内容");
|
|
46
|
+
const number = custom === undefined && /^\d+$/u.test(text) ? Number(text) : undefined;
|
|
47
|
+
if (number !== undefined && (number < 1 || number > item.options.length))
|
|
48
|
+
throw new Error("选项编号超出范围");
|
|
49
|
+
return number !== undefined ? { id: item.id, selected: [item.options[number - 1].label] } : { id: item.id, selected: [], custom: custom ?? text };
|
|
50
|
+
}
|
|
51
|
+
/** 将受信问题的当前题目与原选项投影为终端提示,数字选择与自定义文本共用原Core校验。 */
|
|
52
|
+
export function questionLines(question, index = 0) {
|
|
53
|
+
const item = question.questions[index];
|
|
54
|
+
return item ? [`等待回答(${index + 1}/${question.questions.length}) ${item.header}`, item.question, ...item.options.map(function option(option, n) { return `${n + 1}. ${option.label} — ${option.description}`; }), "输入选项编号,或直接输入自定义答案(纯数字补充用“其他 <内容>”)"] : [];
|
|
55
|
+
}
|
|
37
56
|
/** 创建无 React 依赖的 Controller;Renderer 和 Runtime 均通过参数注入。 */
|
|
38
57
|
export function createCliController(options) {
|
|
39
58
|
const projector = createCliEventProjector({ sessionId: options.sessionId, now: options.now });
|
|
@@ -67,8 +86,8 @@ export function createCliController(options) {
|
|
|
67
86
|
function createPermissionOptions(selectedMode) {
|
|
68
87
|
return [
|
|
69
88
|
{ mode: "ask", label: "询问", description: "查看和新建自动执行;编辑、覆写和每次命令执行询问。", selected: selectedMode === "ask" },
|
|
70
|
-
{ mode: "auto_approve", label: "为我审批", description: "
|
|
71
|
-
{ mode: "full_access", label: "完全访问", description: "
|
|
89
|
+
{ mode: "auto_approve", label: "为我审批", description: "已确认只读及受信项目日常读写、构建和测试自动通过;危险、外部副作用或未知风险仍询问。Windows 命令无 OS 沙箱。", selected: selectedMode === "auto_approve" },
|
|
90
|
+
{ mode: "full_access", label: "完全访问", description: "放行更广范围的普通调用;危险、显式询问和工作区外修改仍需授权,硬拒绝、Trust 与路径校验继续有效。Windows 命令无 OS 沙箱。", selected: selectedMode === "full_access" },
|
|
72
91
|
];
|
|
73
92
|
}
|
|
74
93
|
/** 读取 Composition Root 的 settings-filtered 模型目录,缺失时不假造可切换模型。 */
|
|
@@ -84,12 +103,13 @@ export function createCliController(options) {
|
|
|
84
103
|
/** 将模型与推理配置收窄为状态栏可展示的稳定字符串。 */
|
|
85
104
|
function getConfigLabels(config) {
|
|
86
105
|
const effective = config.effectiveReasoning;
|
|
106
|
+
const capability = config.modelRef ? findModelCapability(config.modelRef.modelId, config.modelRef.provider) : undefined;
|
|
87
107
|
return {
|
|
88
108
|
model: config.modelRef ? `${config.modelRef.provider}/${config.modelRef.modelId}` : "runtime default",
|
|
89
109
|
effort: effective
|
|
90
110
|
? effective.source === "clamped" ? `${effective.effort} (max clamped)` : effective.effort
|
|
91
|
-
: config.reasoningProfile?.effort ?? "runtime default",
|
|
92
|
-
permissionMode: config.permissionMode ?? "ask",
|
|
111
|
+
: config.reasoningProfile?.effort ?? capability?.defaultReasoningEffort ?? (capability?.reasoningCapabilityUnknown ? "供应商默认(能力未知)" : "runtime default"),
|
|
112
|
+
permissionMode: config.executionPermissionMode ?? config.permissionMode ?? "ask",
|
|
93
113
|
};
|
|
94
114
|
}
|
|
95
115
|
/** 读取 Session 默认配置,并只保留权限 picker 所需的安全字段。 */
|
|
@@ -136,7 +156,7 @@ export function createCliController(options) {
|
|
|
136
156
|
const sessionConfig = session?.defaultRunConfig;
|
|
137
157
|
const runtimeDefaults = options.getRuntimeStatusDefaults?.() ?? {};
|
|
138
158
|
const currentProjection = projector.getProjection();
|
|
139
|
-
const isActive =
|
|
159
|
+
const isActive = ["running", "waiting_approval", "waiting_user_input", "interrupted", "interrupted_recoverable", "limit_reached"].includes(currentProjection.status) && Boolean(targetSessionId && targetTurnId);
|
|
140
160
|
const frozen = isActive && options.runtime && targetSessionId && targetTurnId
|
|
141
161
|
? await options.runtime.turns.getFrozenRunConfig({ sessionId: targetSessionId, turnId: targetTurnId })
|
|
142
162
|
: undefined;
|
|
@@ -258,8 +278,7 @@ export function createCliController(options) {
|
|
|
258
278
|
});
|
|
259
279
|
statusRevision++;
|
|
260
280
|
const statusView = await getStatusView();
|
|
261
|
-
const
|
|
262
|
-
const suffix = isActive ? ";当前 Turn 保持 frozen,下一个 Turn 生效" : ";下一个 Turn 生效";
|
|
281
|
+
const suffix = ";下次安全恢复或新回合生效,已经执行的动作不变";
|
|
263
282
|
return result("ok", 0, [`permission: ${permissionLabel(mode)} (${mode})${suffix}`], { statusView });
|
|
264
283
|
}
|
|
265
284
|
let titleWarning;
|
|
@@ -457,6 +476,10 @@ export function createCliController(options) {
|
|
|
457
476
|
const stored = [];
|
|
458
477
|
for (const image of normalized)
|
|
459
478
|
stored.push(await imageStore.put({ sessionId, ...image }));
|
|
479
|
+
if (options.handoffPrompt) {
|
|
480
|
+
const mentions = options.workspaceRoot ? await prepareFileMentionContext(content, options.workspaceRoot) : undefined;
|
|
481
|
+
return result("ok", 0, mentions?.notices ?? [], { preparedPrompt: { content, delivery, attachments: stored, selectedSkills: toInboxSkillRefs(), activeSkills: selectedSkills.map(function active(skill) { return { skillId: skill.skillId, contentHash: skill.contentHash }; }), fileMentions: mentions?.references } });
|
|
482
|
+
}
|
|
460
483
|
const status = submittedStatus;
|
|
461
484
|
if (stored.length === 0 && delivery === undefined && isCliContinuePrompt(content) && status !== "running") {
|
|
462
485
|
const recoverable = await options.runtime.turns.getRecoverableState({ sessionId, turnId });
|
|
@@ -489,13 +512,10 @@ export function createCliController(options) {
|
|
|
489
512
|
}
|
|
490
513
|
/** 当前目标内逐题收集历史问题答案,按精确requestId提交,原文只交给私有问题服务。 */
|
|
491
514
|
let questionDraft;
|
|
492
|
-
/** 将受信问题的当前题目与原选项投影为终端提示,数字选择与自定义文本共用原Core校验。 */
|
|
493
|
-
function questionLines(question, index = 0) {
|
|
494
|
-
const item = question.questions[index];
|
|
495
|
-
return item ? [`等待回答(${index + 1}/${question.questions.length}) ${item.header}`, item.question, ...item.options.map(function option(option, n) { return `${n + 1}. ${option.label} — ${option.description}`; }), "输入选项编号,或直接输入自定义答案(纯数字补充用“其他 <内容>”)"] : [];
|
|
496
|
-
}
|
|
497
515
|
/** 已保存决定先交给受信宿主控制面;无协作组时沿原本机continue入口执行。 */
|
|
498
516
|
async function continueSavedInteraction(input, approval) {
|
|
517
|
+
if (options.handoffPrompt)
|
|
518
|
+
return result("ok", 0, ["交互决定已保存,交由原Host继续。"], { continuationRequested: true });
|
|
499
519
|
const handoff = await options.runtime.turns.requestInteractionContinuation?.(input);
|
|
500
520
|
if (handoff?.queued) {
|
|
501
521
|
const view = await options.runtime.turns.getExecutionState({ sessionId: input.sessionId, turnId: input.turnId }).catch(function unavailable() { return null; });
|
|
@@ -521,16 +541,14 @@ export function createCliController(options) {
|
|
|
521
541
|
if (questionDraft?.requestId !== question.requestId || questionDraft.turnId !== view.turnId)
|
|
522
542
|
questionDraft = { turnId: view.turnId, requestId: question.requestId, answers: [] };
|
|
523
543
|
const item = question.questions[questionDraft.answers.length];
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
return result("error", 2, questionLines(question, questionDraft.answers.length), "选项编号超出范围");
|
|
533
|
-
questionDraft.answers.push(number !== undefined ? { id: item.id, selected: [item.options[number - 1].label] } : { id: item.id, selected: [], custom: custom ?? text });
|
|
544
|
+
if (!item)
|
|
545
|
+
return result("error", 2, [], "当前问题已变化,请刷新后重试");
|
|
546
|
+
try {
|
|
547
|
+
questionDraft.answers.push(parseQuestionAnswer(content, item));
|
|
548
|
+
}
|
|
549
|
+
catch (error) {
|
|
550
|
+
return result("error", 2, questionLines(question, questionDraft.answers.length), error instanceof Error ? error.message : "答案无效");
|
|
551
|
+
}
|
|
534
552
|
if (questionDraft.answers.length < question.questions.length)
|
|
535
553
|
return result("ok", 0, questionLines(question, questionDraft.answers.length));
|
|
536
554
|
if (!options.runtime.questions) {
|
|
@@ -680,6 +698,11 @@ export function createCliController(options) {
|
|
|
680
698
|
return result("error", 2, [], "CLI_TURN_IDENTITY_CHANGED");
|
|
681
699
|
if (decision)
|
|
682
700
|
return await continueSavedInteraction({ sessionId, turnId, approvalId: state.approval.approvalId }, { approvalId: state.approval.approvalId, decision: decision.decision === "deny" ? "deny" : "allow" });
|
|
701
|
+
const statusView = await getStatusView();
|
|
702
|
+
if (generation !== observationGeneration)
|
|
703
|
+
return result("error", 2, [], "CLI_TURN_IDENTITY_CHANGED");
|
|
704
|
+
if (statusView.nextPermissionMode)
|
|
705
|
+
return await consume(options.runtime.turns.continue({ sessionId, turnId }));
|
|
683
706
|
return result("ok", 0, [
|
|
684
707
|
`approval required: ${state.approval?.approvalId ?? "unknown"}${state.approval ? ` (${state.approval.toolName})` : ""}`,
|
|
685
708
|
]);
|
|
@@ -804,10 +827,12 @@ export function createCliController(options) {
|
|
|
804
827
|
const capability = findModelCapability(modelId, provider);
|
|
805
828
|
if (!capability)
|
|
806
829
|
return result("error", 2, [], "MODEL_NOT_SUPPORTED");
|
|
830
|
+
if (capability.supportsToolCalls === false)
|
|
831
|
+
return result("error", 2, [], "MODEL_NOT_SUPPORTED");
|
|
807
832
|
const session = await options.runtime.sessions.get(sessionId);
|
|
808
833
|
if (!session)
|
|
809
834
|
return result("error", 1, [], "SESSION_NOT_FOUND");
|
|
810
|
-
const currentEffort = session.defaultRunConfig?.reasoningProfile?.effort;
|
|
835
|
+
const currentEffort = session.defaultRunConfig?.reasoningProfile?.effort ?? options.getRuntimeStatusDefaults?.().reasoningProfile?.effort;
|
|
811
836
|
if (currentEffort && !capability.requestableEfforts.includes(currentEffort))
|
|
812
837
|
return result("error", 2, [], "REASONING_EFFORT_NOT_SUPPORTED");
|
|
813
838
|
await options.runtime.sessions.setDefaultRunConfig(sessionId, {
|
|
@@ -827,12 +852,13 @@ export function createCliController(options) {
|
|
|
827
852
|
const capability = modelRef ? findModelCapability(modelRef.modelId, modelRef.provider) : undefined;
|
|
828
853
|
if (!capability)
|
|
829
854
|
return result("unavailable", 1, [], "CAPABILITY_UNAVAILABLE: effort_catalog");
|
|
830
|
-
const selectedEffort = session?.defaultRunConfig?.reasoningProfile?.effort ?? options.getRuntimeStatusDefaults?.().reasoningProfile?.effort;
|
|
855
|
+
const selectedEffort = session?.defaultRunConfig?.reasoningProfile?.effort ?? options.getRuntimeStatusDefaults?.().reasoningProfile?.effort ?? capability.defaultReasoningEffort;
|
|
831
856
|
const effortOptions = capability.requestableEfforts.map(function toEffortOption(effort) {
|
|
832
857
|
return { effort, selected: effort === selectedEffort };
|
|
833
858
|
});
|
|
834
859
|
return result("ok", 0, [
|
|
835
860
|
`efforts for ${capability.provider}/${capability.modelId}:`,
|
|
861
|
+
...(effortOptions.length === 0 ? [capability.reasoningCapabilityUnknown ? "供应商默认(能力未知)" : "不支持调整"] : []),
|
|
836
862
|
...effortOptions.map(function formatEffort(option, index) { return `${index + 1}. ${option.effort}${option.selected ? " (selected)" : ""}`; }),
|
|
837
863
|
"interactive: ↑↓ select · Enter save · Esc cancel; plain: /effort <effort>",
|
|
838
864
|
], { statusView, effortOptions });
|
package/dist/design-tokens.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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";
|
package/dist/design-tokens.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** CLI TUI 语义色 token;组件只引用 token,不直接写危险态颜色。 */
|
|
2
|
+
const tuiAccentIndex = 208;
|
|
2
3
|
export const CLI_TUI_COLORS = {
|
|
3
|
-
accent:
|
|
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
|
-
|
|
38
|
-
|
|
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
|
+
}
|
|
@@ -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 {};
|