@autopilot-agent/cli 0.2.0 → 0.3.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 (73) hide show
  1. package/README.md +10 -5
  2. package/dist/activity-animation.d.ts +4 -0
  3. package/dist/activity-animation.js +11 -17
  4. package/dist/composition-root.d.ts +31 -1
  5. package/dist/composition-root.js +112 -3
  6. package/dist/context-report.d.ts +8 -3
  7. package/dist/context-report.js +14 -2
  8. package/dist/controller.d.ts +34 -4
  9. package/dist/controller.js +434 -90
  10. package/dist/error-diagnostics.d.ts +2 -0
  11. package/dist/error-diagnostics.js +3 -1
  12. package/dist/event-projector.d.ts +16 -2
  13. package/dist/event-projector.js +74 -5
  14. package/dist/index.d.ts +1 -1
  15. package/dist/main.js +142 -7
  16. package/dist/parser.js +498 -0
  17. package/dist/renderer.js +3 -1
  18. package/dist/session-summary.d.ts +7 -0
  19. package/dist/session-summary.js +25 -0
  20. package/dist/session-title.d.ts +5 -0
  21. package/dist/session-title.js +10 -0
  22. package/dist/thread-commands.d.ts +37 -0
  23. package/dist/thread-commands.js +233 -0
  24. package/dist/thread-host.d.ts +31 -0
  25. package/dist/thread-host.js +76 -0
  26. package/dist/timeline-lines.js +36 -28
  27. package/dist/tui/app.d.ts +22 -0
  28. package/dist/tui/app.js +112 -40
  29. package/dist/tui/approval.d.ts +4 -0
  30. package/dist/tui/approval.js +13 -4
  31. package/dist/tui/constants.d.ts +1 -1
  32. package/dist/tui/constants.js +1 -1
  33. package/dist/tui/format.d.ts +1 -1
  34. package/dist/tui/format.js +19 -9
  35. package/dist/tui/hooks/use-prompt-input.d.ts +52 -0
  36. package/dist/tui/hooks/use-prompt-input.js +148 -20
  37. package/dist/tui/hooks/use-status-view.d.ts +2 -2
  38. package/dist/tui/hooks/use-status-view.js +38 -11
  39. package/dist/tui/inline-output.d.ts +17 -0
  40. package/dist/tui/inline-output.js +31 -0
  41. package/dist/tui/input/clipboard-image.d.ts +17 -0
  42. package/dist/tui/input/clipboard-image.js +117 -0
  43. package/dist/tui/input-area.d.ts +8 -0
  44. package/dist/tui/input-area.js +18 -3
  45. package/dist/tui/lifecycle.js +2 -5
  46. package/dist/tui/markdown/diff.d.ts +1 -1
  47. package/dist/tui/markdown/diff.js +28 -1
  48. package/dist/tui/performance-diagnostics.js +2 -0
  49. package/dist/tui/prompt-input.d.ts +1 -0
  50. package/dist/tui/prompt-input.js +5 -3
  51. package/dist/tui/render-mode.d.ts +4 -4
  52. package/dist/tui/render-mode.js +5 -11
  53. package/dist/tui/run.js +37 -49
  54. package/dist/tui/session-manager.d.ts +115 -0
  55. package/dist/tui/session-manager.js +383 -0
  56. package/dist/tui/session-workspace.d.ts +9 -0
  57. package/dist/tui/session-workspace.js +383 -0
  58. package/dist/tui/status-line.d.ts +3 -0
  59. package/dist/tui/status-line.js +12 -6
  60. package/dist/tui/store.js +27 -5
  61. package/dist/tui/timeline/live.js +2 -3
  62. package/dist/tui/timeline/progress.js +3 -2
  63. package/dist/tui/timeline/static-timeline.js +1 -2
  64. package/dist/tui/timeline/turn.js +3 -2
  65. package/dist/tui/transcript.d.ts +1 -1
  66. package/dist/tui/transcript.js +19 -1
  67. package/dist/tui/trust-dialog.d.ts +3 -0
  68. package/dist/tui/trust-dialog.js +23 -2
  69. package/dist/tui/types.d.ts +8 -0
  70. package/dist/tui/types.js +4 -1
  71. package/dist/tui/viewport/sources.js +6 -13
  72. package/dist/types.d.ts +152 -2
  73. package/package.json +4 -4
@@ -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);
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@ export type { CliApprovalSubmit, CliController, CliControllerResult, CreateCliCo
13
13
  export { createCliEventProjector, createInitialCliProjection, reduceCliEvent } from "./event-projector.js";
14
14
  export { createPlainRenderer } from "./renderer.js";
15
15
  export { parseArgv, parseSlashAction, renderHelp } from "./parser.js";
16
- export type { CliAction, CliActionParseResult, CliCommand, CliEventEnvelope, CliEventListener, CliQueuedInputStarted, CliQueuedInputStartedListener, CliExitCode, CliHostOptions, CliInvocation, CliOutputFormat, CliPermissionMode, CliPermissionOption, CliParseResult, CliProjection, CliPublicEvent, CliRenderer, CliStatusView, CliRuntime, CliTurnStatus, } from "./types.js";
16
+ export type { CliAction, CliActionParseResult, CliCommand, CliEventEnvelope, CliEventListener, CliQueuedInputStarted, CliQueuedInputStartedListener, CliExitCode, CliHostOptions, CliInvocation, CliOutputFormat, CliPermissionMode, CliPermissionOption, CliParseResult, CliProjection, CliPublicEvent, CliRenderer, CliStatusView, CliRuntime, CliThreadCommand, CliThreadMode, CliTurnStatus, } from "./types.js";
17
17
  export { createCliTuiStore, runCliTui } from "./tui.js";
18
18
  export type { CliTuiInitialOperation, CliTuiRecap, CliTuiSnapshot, CliTuiStore, CliTuiTranscriptItem, RunCliTuiOptions, RunCliTuiResult, } from "./tui.js";
19
19
  export { formatCliTuiRecap } from "./tui.js";
package/dist/main.js CHANGED
@@ -5,17 +5,19 @@
5
5
  * 入口只负责 argv、Composition Root、Plain Controller 和进程生命周期的编排;
6
6
  * Session、Turn、审批、恢复和持久化规则全部委托给 Core Runtime。
7
7
  */
8
+ import { createCliSessionManager } from "./tui/session-manager.js";
8
9
  import { WEB_SEARCH_DATA_FLOW_NOTICE } from "@autopilot-agent/presentation";
9
10
  import path from "node:path";
10
11
  import fs from "node:fs";
11
12
  import readline from "node:readline";
12
13
  import { pathToFileURL } from "node:url";
13
- import { AgentRuntimeError, WorkspaceTrustError, } from "@autopilot-agent/core";
14
+ import { AgentRuntimeError, ThreadServiceError, WorkspaceTrustError, } from "@autopilot-agent/core";
14
15
  import { createCliCompositionRoot } from "./composition-root.js";
15
16
  import { createCliController } from "./controller.js";
16
- import { classifyCliError } from "./error-diagnostics.js";
17
+ import { classifyCliError, CLI_THREAD_RECOVERY_HINT } from "./error-diagnostics.js";
17
18
  import { parseArgv, parseSlashAction, renderHelp } from "./parser.js";
18
19
  import { createPlainRenderer } from "./renderer.js";
20
+ import { CliThreadInputError, executeThreadCommand } from "./thread-commands.js";
19
21
  import { runCliTui, runCliTrustDialog } from "./tui.js";
20
22
  /** 将宿主信号映射为固定 CLI 退出码。 */
21
23
  export function exitCodeForSignal(signal) {
@@ -34,8 +36,20 @@ function formatCliError(error) {
34
36
  const classification = classifyCliError(error);
35
37
  if (classification.category === "config_directory")
36
38
  return classification.code;
39
+ if (classification.category === "node_state") {
40
+ const messages = {
41
+ STATE_SCHEMA_VERSION_UNSUPPORTED: "状态数据来自不支持的版本,请更新程序后重试;现有数据已保留",
42
+ STATE_SCHEMA_BUSY: "状态数据正在使用或升级,请停止其他运行实例后重试",
43
+ STATE_SCHEMA_MIGRATION_FAILED: "状态升级未完成,原数据和恢复备份已保留,请停止其他运行实例后重试;仍失败请联系支持",
44
+ STATE_SCHEMA_MIGRATION_MISSING: "缺少状态升级步骤,请更新程序后重试;现有数据已保留",
45
+ STATE_SCHEMA_RECOVERY_REQUIRED: "状态需要恢复,原数据已保留,请停止其他运行实例后重试;仍失败请联系支持",
46
+ };
47
+ return `${classification.code}${Object.hasOwn(messages, classification.code) ? `: ${messages[classification.code]}` : ""}`;
48
+ }
37
49
  if (error instanceof WorkspaceTrustError)
38
50
  return `WORKSPACE_TRUST_REQUIRED: ${error.status}`;
51
+ if (error instanceof AgentRuntimeError && error.code === "THREAD_RECOVERY_REQUIRED")
52
+ return `${error.code}: ${CLI_THREAD_RECOVERY_HINT}`;
39
53
  if (error instanceof AgentRuntimeError)
40
54
  return `${error.code}: ${sanitizeErrorMessage(error.message)}`;
41
55
  return "CLI_RUNTIME_ERROR";
@@ -72,6 +86,18 @@ function sanitizeManagementString(value) {
72
86
  .replace(/(?:[A-Za-z]:[\\/]|\\\\|\/(?:Users|home|private|tmp|var|mnt|workspace|Volumes)\/)[^\s"'`]+/gu, "[path]")
73
87
  .replace(/\b(api[_-]?key|access[_-]?token|password|secret|dsn)\s*[:=]\s*[^\s,;]+/giu, "$1=[redacted]");
74
88
  }
89
+ /** 协作结果直接输出 JSON;内容已由 Core 做安全投影与限额,这里不改写正文。 */
90
+ function writeThreadResult(streams, value) {
91
+ streams.stdout.write(`${JSON.stringify(value)}\n`);
92
+ }
93
+ /** 读取全部 stdin;只在命令显式要求 --message-stdin 时调用,避免误吞交互输入。 */
94
+ async function readStdinText(streams) {
95
+ const input = streams.stdin ?? process.stdin;
96
+ let text = "";
97
+ for await (const chunk of input)
98
+ text += String(chunk);
99
+ return text;
100
+ }
75
101
  /** 将 Core 安全 JobView 补充独立命令所需身份,不读取命令、路径、PID 或 owner。 */
76
102
  function summarizeJob(job, view) {
77
103
  return {
@@ -140,7 +166,7 @@ async function ensureProject(runtime, workspaceRoot) {
140
166
  return runtime.projects.create({ name: path.basename(workspaceRoot) || "project", workspaceRoot });
141
167
  }
142
168
  /** 读取指定 Session 或创建当前 Project 下的新 Session。 */
143
- async function ensureChatSession(runtime, project, sessionId, prompt) {
169
+ async function ensureChatSession(runtime, project, sessionId) {
144
170
  if (sessionId) {
145
171
  const session = await runtime.sessions.get(sessionId);
146
172
  if (!session)
@@ -151,13 +177,14 @@ async function ensureChatSession(runtime, project, sessionId, prompt) {
151
177
  }
152
178
  return runtime.sessions.create({
153
179
  projectId: project.id,
154
- title: prompt?.trim().slice(0, 80),
180
+ // 统一由Controller在首个有效交互时建立短标题,成功回答后沿Web范式更新。
181
+ title: undefined,
155
182
  });
156
183
  }
157
184
  /** 读取指定或最近的可恢复 Session;没有可用 Session 时返回稳定错误。 */
158
185
  async function selectResumeSession(runtime, project, sessionId) {
159
186
  if (sessionId)
160
- return ensureChatSession(runtime, project, sessionId, undefined);
187
+ return ensureChatSession(runtime, project, sessionId);
161
188
  const sessions = (await runtime.sessions.list())
162
189
  .filter(function selectProjectSession(item) { return !item.projectId || item.projectId === project.id; })
163
190
  .sort(function sortRecent(left, right) { return right.updatedAt - left.updatedAt; });
@@ -242,6 +269,61 @@ async function runInputLoop(controller, format, streams, signalSource, showPromp
242
269
  signalSource.removeListener("SIGTERM", handleSigterm);
243
270
  }
244
271
  }
272
+ /**
273
+ * 执行协作薄命令。
274
+ *
275
+ * 只绑定当前 Project 并复用 Runtime 的同一份 Ports;不启动常驻 Runner,
276
+ * 因此回执只表示消息已接受,执行仍取决于是否有在线宿主。
277
+ */
278
+ async function executeThreadInvocation(command, root, runtime, workspaceRoot, streams, signalSource) {
279
+ // 协作组绑定到已存在的 Project;读取命令不为查询新建 Project。
280
+ const project = (await runtime.projects.list()).find(function matchWorkspace(item) { return item.workspaceRoot === workspaceRoot; });
281
+ if (!project) {
282
+ streams.stderr.write("THREADS_UNAVAILABLE: 当前工作区尚未建立 Project\n");
283
+ return 1;
284
+ }
285
+ root.bindThreadsProject(project.id);
286
+ const threads = root.createHumanThreads();
287
+ const controller = new AbortController();
288
+ let requestedExitCode;
289
+ /** 中断只结束本地观察或等待,不向任何目标提交取消。 */
290
+ function handleSignal(signal) {
291
+ requestedExitCode = exitCodeForSignal(signal);
292
+ controller.abort();
293
+ }
294
+ function handleSigint() { handleSignal("SIGINT"); }
295
+ function handleSigterm() { handleSignal("SIGTERM"); }
296
+ signalSource.on("SIGINT", handleSigint);
297
+ signalSource.on("SIGTERM", handleSigterm);
298
+ try {
299
+ const executed = await executeThreadCommand(command, {
300
+ threads,
301
+ readFile: function readFile(file) { return fs.promises.readFile(file, "utf8"); },
302
+ readStdin: function readStdin() { return readStdinText(streams); },
303
+ write: function write(line) { streams.stdout.write(`${line}\n`); },
304
+ signal: controller.signal,
305
+ });
306
+ if (executed.result !== undefined)
307
+ writeThreadResult(streams, executed.result);
308
+ return requestedExitCode ?? executed.exitCode;
309
+ }
310
+ catch (error) {
311
+ if (error instanceof CliThreadInputError) {
312
+ streams.stderr.write(`${error.message}\n`);
313
+ return 2;
314
+ }
315
+ if (error instanceof ThreadServiceError) {
316
+ // 参数类错误按 usage 退出码,其余按运行期失败;错误码本身足以定位,不回显路径。
317
+ streams.stderr.write(`${error.code}\n`);
318
+ return error.code === "INVALID_INPUT" || error.code === "MODEL_NOT_FOUND" ? 2 : 1;
319
+ }
320
+ throw error;
321
+ }
322
+ finally {
323
+ signalSource.removeListener("SIGINT", handleSigint);
324
+ signalSource.removeListener("SIGTERM", handleSigterm);
325
+ }
326
+ }
245
327
  /** 执行已经通过 parser 校验的 CLI 命令。 */
246
328
  async function executeInvocation(invocation, streams, dependencies) {
247
329
  const command = invocation.command;
@@ -361,7 +443,12 @@ async function executeInvocation(invocation, streams, dependencies) {
361
443
  return 0;
362
444
  }
363
445
  const runtime = await root.createRuntime(trust.workspaceRoot);
446
+ let threadHost;
447
+ let sessionManager;
364
448
  try {
449
+ if (command.type === "thread") {
450
+ return await executeThreadInvocation(command.command, root, runtime, trust.workspaceRoot, streams, signalSource);
451
+ }
365
452
  if (command.type === "job_list" || command.type === "job_show" || command.type === "job_output" || command.type === "job_kill") {
366
453
  if (command.type === "job_list") {
367
454
  const jobs = await runtime.jobs.list(trust.workspaceRoot);
@@ -443,9 +530,13 @@ async function executeInvocation(invocation, streams, dependencies) {
443
530
  return 1;
444
531
  }
445
532
  const project = await ensureProject(runtime, trust.workspaceRoot);
533
+ // 协作范围按 Project 绑定;常驻宿主发现已启用组后才接管驱动,未启用时保持轻量复查。
534
+ 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();
446
537
  const session = command.type === "resume"
447
538
  ? await selectResumeSession(runtime, project, command.sessionId)
448
- : await ensureChatSession(runtime, project, command.sessionId, command.prompt);
539
+ : await ensureChatSession(runtime, project, command.sessionId);
449
540
  const renderer = command.output === "interactive" && hasTty
450
541
  ? { format: "text", render: function renderTuiEvent() { return ""; } }
451
542
  : createPlainRenderer(command.output === "jsonl" ? "jsonl" : "text");
@@ -457,8 +548,9 @@ async function executeInvocation(invocation, streams, dependencies) {
457
548
  getRuntimeStatusDefaults: root.getRuntimeStatusDefaults,
458
549
  listSkills: root.listSkills,
459
550
  resolveSkill: root.resolveSkill,
551
+ registerExecution: threadHost.registerExecution,
460
552
  });
461
- const recoverable = command.type === "chat" && !command.prompt
553
+ const recoverable = command.type === "chat" && !command.prompt && (command.output !== "interactive" || !hasTty)
462
554
  ? await runtime.turns.getRecoverableState({ sessionId: session.id })
463
555
  : undefined;
464
556
  if (recoverable?.recoverable && recoverable.status === "awaiting_user_input") {
@@ -472,7 +564,42 @@ async function executeInvocation(invocation, streams, dependencies) {
472
564
  : command.prompt
473
565
  ? { type: "start", content: command.prompt }
474
566
  : undefined;
567
+ sessionManager = createCliSessionManager({
568
+ 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 }); },
570
+ /** 通过既有人类只读目录查询创建/关联事实,分页不启动任何目标。 */
571
+ readRelations: async function readRelations(sessionId, signal) {
572
+ signal?.throwIfAborted();
573
+ const threads = root.createHumanThreads();
574
+ const { group } = await threads.groupOf({ protocolVersion: 1, threadId: sessionId });
575
+ signal?.throwIfAborted();
576
+ if (!group)
577
+ return [];
578
+ const items = [];
579
+ let cursor;
580
+ do {
581
+ signal?.throwIfAborted();
582
+ const page = await threads.list({ protocolVersion: 1, groupId: group.groupId, limit: 100, cursor });
583
+ for (const item of page.items) {
584
+ const parentThreadId = item.parentThreadId ?? (item.threadId === group.rootThreadId ? null : group.rootThreadId);
585
+ if (parentThreadId !== sessionId)
586
+ continue;
587
+ signal?.throwIfAborted();
588
+ const summary = await root.readSessionSummary(item.threadId, signal);
589
+ if (summary)
590
+ items.push({ threadId: item.threadId, parentThreadId, title: summary.title, status: summary.status, activeTurnId: summary.currentTurnId ?? summary.activeTurnId, executionView: summary.executionView });
591
+ }
592
+ cursor = page.nextCursor;
593
+ } while (cursor);
594
+ return items;
595
+ },
596
+ readDirectoryPage: function directory(input) { return root.readSessionDirectoryPage(project.id, input); },
597
+ readSummary: root.readSessionSummary,
598
+ readEventPage: root.readSessionEventPage,
599
+ });
600
+ sessionManager.start();
475
601
  const tuiResult = await runCliTui({
602
+ sessionManager,
476
603
  controller,
477
604
  sessionId: session.id,
478
605
  workspaceRoot: trust.workspaceRoot,
@@ -514,6 +641,14 @@ async function executeInvocation(invocation, streams, dependencies) {
514
641
  return resumed.exitCode;
515
642
  }
516
643
  finally {
644
+ const sessionsStopped = await sessionManager?.stop();
645
+ const stopReport = await threadHost?.stop();
646
+ if (sessionsStopped)
647
+ streams.stderr.write(`宿主退出:确认停止=${sessionsStopped.stopped.length} 等待审批或输入=${sessionsStopped.waiting.length} 可恢复=${sessionsStopped.recoverable.length} 未确认=${sessionsStopped.unconfirmed.length}\n`);
648
+ // 停机报告只陈述事实:取消与未确认项必须显式可见,不能写成目标已完成。
649
+ if (stopReport) {
650
+ 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
+ }
517
652
  await runtime.shutdown?.();
518
653
  }
519
654
  }