ycodium-acp-executor 0.2.5542 → 0.2.5751

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 (251) hide show
  1. package/README.md +5 -4
  2. package/dist/_private/ycodium-jsonl-stream/appendedJsonl.d.ts +47 -0
  3. package/dist/_private/ycodium-jsonl-stream/appendedJsonl.js +172 -0
  4. package/dist/_private/ycodium-jsonl-stream/claudeSessions.d.ts +63 -0
  5. package/dist/_private/ycodium-jsonl-stream/claudeSessions.js +220 -0
  6. package/dist/_private/ycodium-jsonl-stream/codexSessions.d.ts +41 -0
  7. package/dist/_private/ycodium-jsonl-stream/codexSessions.js +197 -0
  8. package/dist/_private/ycodium-jsonl-stream/history.d.ts +6 -0
  9. package/dist/_private/ycodium-jsonl-stream/history.js +389 -0
  10. package/dist/_private/ycodium-jsonl-stream/historyErrors.d.ts +6 -0
  11. package/dist/_private/ycodium-jsonl-stream/historyErrors.js +6 -0
  12. package/dist/_private/ycodium-jsonl-stream/historyFile.d.ts +19 -0
  13. package/dist/_private/ycodium-jsonl-stream/historyFile.js +117 -0
  14. package/dist/_private/ycodium-jsonl-stream/historyRecord.d.ts +31 -0
  15. package/dist/_private/ycodium-jsonl-stream/historyRecord.js +144 -0
  16. package/dist/_private/ycodium-jsonl-stream/historyWaiting.d.ts +8 -0
  17. package/dist/_private/ycodium-jsonl-stream/historyWaiting.js +142 -0
  18. package/dist/_private/ycodium-jsonl-stream/jsonObjectLine.d.ts +5 -0
  19. package/dist/_private/ycodium-jsonl-stream/jsonObjectLine.js +18 -0
  20. package/dist/_private/ycodium-jsonl-stream/jsonlStream.d.ts +79 -0
  21. package/dist/_private/ycodium-jsonl-stream/jsonlStream.js +603 -0
  22. package/dist/_private/ycodium-jsonl-stream/scanCache.d.ts +69 -0
  23. package/dist/_private/ycodium-jsonl-stream/scanCache.js +106 -0
  24. package/dist/_private/ycodium-jsonl-stream/sessionDirectory.d.ts +5 -0
  25. package/dist/_private/ycodium-jsonl-stream/sessionDirectory.js +32 -0
  26. package/dist/_private/ycodium-jsonl-stream/sessionTranscript.d.ts +3 -1
  27. package/dist/_private/ycodium-jsonl-stream/sessionTranscript.js +13 -0
  28. package/dist/_private/ycodium-jsonl-stream/usageFields.d.ts +5 -0
  29. package/dist/_private/ycodium-jsonl-stream/usageFields.js +11 -0
  30. package/dist/_private/ycodium-workspace-path/directoryScope.d.ts +5 -0
  31. package/dist/_private/ycodium-workspace-path/directoryScope.js +28 -0
  32. package/dist/_private/ycodium-workspace-path/workspacePath.d.ts +19 -0
  33. package/dist/_private/ycodium-workspace-path/workspacePath.js +90 -0
  34. package/dist/adapter-support.d.ts.map +1 -1
  35. package/dist/adapter-support.js.map +1 -1
  36. package/dist/apply-effort.d.ts.map +1 -1
  37. package/dist/apply-effort.js.map +1 -1
  38. package/dist/approvals.d.ts.map +1 -1
  39. package/dist/approvals.js.map +1 -1
  40. package/dist/artifacts.d.ts.map +1 -1
  41. package/dist/artifacts.js.map +1 -1
  42. package/dist/card-defaults.d.ts.map +1 -1
  43. package/dist/card-defaults.js.map +1 -1
  44. package/dist/config-option-wiring.d.ts.map +1 -1
  45. package/dist/config-option-wiring.js.map +1 -1
  46. package/dist/config-options.d.ts.map +1 -1
  47. package/dist/config-options.js.map +1 -1
  48. package/dist/connection.d.ts.map +1 -1
  49. package/dist/connection.js.map +1 -1
  50. package/dist/errors.d.ts.map +1 -1
  51. package/dist/errors.js.map +1 -1
  52. package/dist/event-stream.d.ts.map +1 -1
  53. package/dist/event-stream.js.map +1 -1
  54. package/dist/events.d.ts.map +1 -1
  55. package/dist/events.js.map +1 -1
  56. package/dist/executor/child-sessions.d.ts.map +1 -1
  57. package/dist/executor/child-sessions.js.map +1 -1
  58. package/dist/executor/lifecycle.d.ts.map +1 -1
  59. package/dist/executor/lifecycle.js.map +1 -1
  60. package/dist/executor/prompt-results.d.ts.map +1 -1
  61. package/dist/executor/prompt-results.js.map +1 -1
  62. package/dist/executor/prompt.d.ts.map +1 -1
  63. package/dist/executor/prompt.js.map +1 -1
  64. package/dist/executor/requests.d.ts.map +1 -1
  65. package/dist/executor/requests.js.map +1 -1
  66. package/dist/executor/runtime.d.ts.map +1 -1
  67. package/dist/executor/runtime.js.map +1 -1
  68. package/dist/executor/session.d.ts.map +1 -1
  69. package/dist/executor/session.js +17 -1
  70. package/dist/executor/session.js.map +1 -1
  71. package/dist/executor/settlement.d.ts.map +1 -1
  72. package/dist/executor/settlement.js.map +1 -1
  73. package/dist/executor/subagent-sessions.d.ts.map +1 -1
  74. package/dist/executor/subagent-sessions.js.map +1 -1
  75. package/dist/executor/support.d.ts.map +1 -1
  76. package/dist/executor/support.js.map +1 -1
  77. package/dist/executor/updates.d.ts.map +1 -1
  78. package/dist/executor/updates.js +11 -0
  79. package/dist/executor/updates.js.map +1 -1
  80. package/dist/executor.d.ts.map +1 -1
  81. package/dist/executor.js.map +1 -1
  82. package/dist/failureCategory.d.ts.map +1 -1
  83. package/dist/failureCategory.js.map +1 -1
  84. package/dist/handshake.d.ts.map +1 -1
  85. package/dist/handshake.js.map +1 -1
  86. package/dist/index.d.ts +2 -2
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +2 -2
  89. package/dist/index.js.map +1 -1
  90. package/dist/instance-kit.d.ts.map +1 -1
  91. package/dist/instance-kit.js.map +1 -1
  92. package/dist/jsonrpc.d.ts.map +1 -1
  93. package/dist/jsonrpc.js.map +1 -1
  94. package/dist/line-buffer.d.ts.map +1 -1
  95. package/dist/line-buffer.js.map +1 -1
  96. package/dist/mcp-servers.d.ts +26 -4
  97. package/dist/mcp-servers.d.ts.map +1 -1
  98. package/dist/mcp-servers.js +25 -4
  99. package/dist/mcp-servers.js.map +1 -1
  100. package/dist/model-selection.d.ts.map +1 -1
  101. package/dist/model-selection.js.map +1 -1
  102. package/dist/model-send.d.ts.map +1 -1
  103. package/dist/model-send.js.map +1 -1
  104. package/dist/mutex.d.ts.map +1 -1
  105. package/dist/mutex.js.map +1 -1
  106. package/dist/native-session-transcript.d.ts.map +1 -1
  107. package/dist/native-session-transcript.js.map +1 -1
  108. package/dist/native-sessions.d.ts.map +1 -1
  109. package/dist/native-sessions.js.map +1 -1
  110. package/dist/openCommands.d.ts.map +1 -1
  111. package/dist/openCommands.js.map +1 -1
  112. package/dist/permission-statement.d.ts.map +1 -1
  113. package/dist/permission-statement.js.map +1 -1
  114. package/dist/probe-process.d.ts +9 -5
  115. package/dist/probe-process.d.ts.map +1 -1
  116. package/dist/probe-process.js +4 -0
  117. package/dist/probe-process.js.map +1 -1
  118. package/dist/probe-session.d.ts.map +1 -1
  119. package/dist/probe-session.js.map +1 -1
  120. package/dist/probe.d.ts.map +1 -1
  121. package/dist/probe.js.map +1 -1
  122. package/dist/prompt-dispatch.d.ts.map +1 -1
  123. package/dist/prompt-dispatch.js.map +1 -1
  124. package/dist/protocol-log.d.ts.map +1 -1
  125. package/dist/protocol-log.js.map +1 -1
  126. package/dist/protocol.d.ts.map +1 -1
  127. package/dist/protocol.js.map +1 -1
  128. package/dist/refreshDeadline.d.ts.map +1 -1
  129. package/dist/refreshDeadline.js.map +1 -1
  130. package/dist/runtime-mode.d.ts.map +1 -1
  131. package/dist/runtime-mode.js.map +1 -1
  132. package/dist/runtime-model.d.ts +4 -0
  133. package/dist/runtime-model.d.ts.map +1 -1
  134. package/dist/runtime-model.js +13 -0
  135. package/dist/runtime-model.js.map +1 -1
  136. package/dist/session-cleanup.d.ts.map +1 -1
  137. package/dist/session-cleanup.js.map +1 -1
  138. package/dist/session-registry.d.ts.map +1 -1
  139. package/dist/session-registry.js.map +1 -1
  140. package/dist/session-update.d.ts.map +1 -1
  141. package/dist/session-update.js.map +1 -1
  142. package/dist/sessionProcess.d.ts.map +1 -1
  143. package/dist/sessionProcess.js.map +1 -1
  144. package/dist/source/_private/ycodium-executor-common/catalogModel.ts +40 -0
  145. package/dist/source/_private/ycodium-executor-common/eventTypes.ts +97 -0
  146. package/dist/source/_private/ycodium-executor-common/modelSelection.ts +24 -0
  147. package/dist/source/_private/ycodium-executor-common/nodeStreams.ts +212 -0
  148. package/dist/source/_private/ycodium-executor-common/raceAbort.ts +25 -0
  149. package/dist/source/_private/ycodium-executor-common/reasoningLevelFallback.ts +28 -0
  150. package/dist/source/_private/ycodium-executor-common/stderrTail.ts +27 -0
  151. package/dist/source/_private/ycodium-executor-common/toolPresentation.ts +268 -0
  152. package/dist/source/_private/ycodium-jsonl-stream/appendedJsonl.ts +222 -0
  153. package/dist/source/_private/ycodium-jsonl-stream/claudeSessions.ts +263 -0
  154. package/dist/source/_private/ycodium-jsonl-stream/codexSessions.ts +254 -0
  155. package/dist/source/_private/ycodium-jsonl-stream/history.ts +492 -0
  156. package/dist/source/_private/ycodium-jsonl-stream/historyErrors.ts +6 -0
  157. package/dist/source/_private/ycodium-jsonl-stream/historyFile.ts +139 -0
  158. package/dist/source/_private/ycodium-jsonl-stream/historyRecord.ts +180 -0
  159. package/dist/source/_private/ycodium-jsonl-stream/historyWaiting.ts +140 -0
  160. package/dist/source/_private/ycodium-jsonl-stream/jsonObjectLine.ts +15 -0
  161. package/dist/source/_private/ycodium-jsonl-stream/jsonlStream.ts +650 -0
  162. package/dist/source/_private/ycodium-jsonl-stream/scanCache.ts +163 -0
  163. package/dist/source/_private/ycodium-jsonl-stream/sessionDirectory.ts +39 -0
  164. package/dist/source/_private/ycodium-jsonl-stream/sessionTranscript.ts +136 -0
  165. package/dist/source/_private/ycodium-jsonl-stream/usageFields.ts +13 -0
  166. package/dist/source/_private/ycodium-workspace-path/directoryScope.ts +34 -0
  167. package/dist/source/_private/ycodium-workspace-path/workspacePath.ts +110 -0
  168. package/dist/source/adapter-support.ts +115 -0
  169. package/dist/source/apply-effort.ts +66 -0
  170. package/dist/source/approvals.ts +94 -0
  171. package/dist/source/artifacts.ts +88 -0
  172. package/dist/source/card-defaults.ts +25 -0
  173. package/dist/source/config-option-wiring.ts +119 -0
  174. package/dist/source/config-options.ts +270 -0
  175. package/dist/source/connection.ts +553 -0
  176. package/dist/source/errors.ts +207 -0
  177. package/dist/source/event-stream.ts +91 -0
  178. package/dist/source/events.ts +341 -0
  179. package/dist/source/executor/child-sessions.ts +87 -0
  180. package/dist/source/executor/lifecycle.ts +282 -0
  181. package/dist/source/executor/prompt-results.ts +123 -0
  182. package/dist/source/executor/prompt.ts +606 -0
  183. package/dist/source/executor/requests.ts +323 -0
  184. package/dist/source/executor/runtime.ts +137 -0
  185. package/dist/source/executor/session.ts +553 -0
  186. package/dist/source/executor/settlement.ts +92 -0
  187. package/dist/source/executor/subagent-sessions.ts +183 -0
  188. package/dist/source/executor/support.ts +129 -0
  189. package/dist/source/executor/updates.ts +427 -0
  190. package/dist/source/executor.ts +537 -0
  191. package/dist/source/failureCategory.ts +74 -0
  192. package/dist/source/handshake.ts +66 -0
  193. package/dist/source/index.ts +210 -0
  194. package/dist/source/instance-kit.ts +478 -0
  195. package/dist/source/jsonrpc.ts +59 -0
  196. package/dist/source/line-buffer.ts +54 -0
  197. package/dist/source/mcp-servers.ts +83 -0
  198. package/dist/source/model-selection.ts +138 -0
  199. package/dist/source/model-send.ts +80 -0
  200. package/dist/source/mutex.ts +47 -0
  201. package/dist/source/native-session-transcript.ts +167 -0
  202. package/dist/source/native-sessions.ts +271 -0
  203. package/dist/source/openCommands.ts +39 -0
  204. package/dist/source/permission-statement.ts +49 -0
  205. package/dist/source/probe-process.ts +95 -0
  206. package/dist/source/probe-session.ts +81 -0
  207. package/dist/source/probe.ts +261 -0
  208. package/dist/source/prompt-dispatch.ts +42 -0
  209. package/dist/source/protocol-log.ts +143 -0
  210. package/dist/source/protocol.ts +36 -0
  211. package/dist/source/refreshDeadline.ts +2 -0
  212. package/dist/source/runtime-mode.ts +125 -0
  213. package/dist/source/runtime-model.ts +598 -0
  214. package/dist/source/session-cleanup.ts +82 -0
  215. package/dist/source/session-registry.ts +62 -0
  216. package/dist/source/session-update.ts +88 -0
  217. package/dist/source/sessionProcess.ts +29 -0
  218. package/dist/source/start-abort.ts +19 -0
  219. package/dist/source/thread-operations.ts +145 -0
  220. package/dist/source/tool-call-state.ts +322 -0
  221. package/dist/source/tool-presentation.ts +20 -0
  222. package/dist/source/tool-subagents.ts +491 -0
  223. package/dist/source/turn-usage.ts +78 -0
  224. package/dist/source/types.ts +146 -0
  225. package/dist/source/user-input-pending.ts +31 -0
  226. package/dist/source/util.ts +38 -0
  227. package/dist/source/vendor-hooks.ts +394 -0
  228. package/dist/start-abort.d.ts.map +1 -1
  229. package/dist/start-abort.js.map +1 -1
  230. package/dist/thread-operations.d.ts.map +1 -1
  231. package/dist/thread-operations.js.map +1 -1
  232. package/dist/tool-call-state.d.ts.map +1 -1
  233. package/dist/tool-call-state.js.map +1 -1
  234. package/dist/tool-presentation.d.ts.map +1 -1
  235. package/dist/tool-presentation.js.map +1 -1
  236. package/dist/tool-subagents.d.ts +1 -0
  237. package/dist/tool-subagents.d.ts.map +1 -1
  238. package/dist/tool-subagents.js +2 -0
  239. package/dist/tool-subagents.js.map +1 -1
  240. package/dist/turn-usage.d.ts.map +1 -1
  241. package/dist/turn-usage.js.map +1 -1
  242. package/dist/types.d.ts.map +1 -1
  243. package/dist/types.js.map +1 -1
  244. package/dist/user-input-pending.d.ts.map +1 -1
  245. package/dist/user-input-pending.js.map +1 -1
  246. package/dist/util.d.ts.map +1 -1
  247. package/dist/util.js.map +1 -1
  248. package/dist/vendor-hooks.d.ts +11 -3
  249. package/dist/vendor-hooks.d.ts.map +1 -1
  250. package/dist/vendor-hooks.js.map +1 -1
  251. package/package.json +5 -2
@@ -0,0 +1,207 @@
1
+ // @effect-diagnostics globalTimers:off
2
+ import { lastStderrTail } from "./_private/ycodium-executor-common/stderrTail.ts";
3
+
4
+ export class AcpExecutorError extends Error {
5
+ readonly code: string;
6
+
7
+ constructor(code: string, message: string) {
8
+ super(message);
9
+ this.name = "AcpExecutorError";
10
+ this.code = code;
11
+ }
12
+ }
13
+
14
+ export class AcpExecutorDisposedError extends AcpExecutorError {
15
+ constructor(message = "ACP executor has been disposed") {
16
+ super("disposed", message);
17
+ this.name = "AcpExecutorDisposedError";
18
+ }
19
+ }
20
+
21
+ /**
22
+ * 插话的目标轮已经不是活动轮。抛出时还没写给对端,确定没投递,所以 `code` 用宿主认的
23
+ * `provider-rejected`:宿主把这条输入原样还回去,改作新的一轮。
24
+ */
25
+ export class AcpExecutorTurnEndedError extends AcpExecutorError {
26
+ constructor(message = "The target turn has ended. The message was not sent.") {
27
+ super("provider-rejected", message);
28
+ this.name = "AcpExecutorTurnEndedError";
29
+ }
30
+ }
31
+
32
+ /**
33
+ * 发送前在会话里切型号或思考档,agent 拒了。这一轮的提示词没写出去,确定没投递,`code` 用宿主认的
34
+ * `provider-rejected`,原句透给用户;会话不关,下一轮照常再对齐。
35
+ */
36
+ export class AcpExecutorOptionRejectedError extends AcpExecutorError {
37
+ constructor(option: "model" | "reasoning level", value: string | undefined, cause: unknown) {
38
+ const detail = acpErrorDetail(cause);
39
+ super(
40
+ "provider-rejected",
41
+ `The agent rejected the ${option}${value === undefined ? "" : ` "${value}"`}${
42
+ detail === undefined ? "" : ` (${detail})`
43
+ }. This turn was not sent.`,
44
+ );
45
+ this.name = "AcpExecutorOptionRejectedError";
46
+ }
47
+ }
48
+
49
+ /**
50
+ * 发送前切型号或思考档,agent 在期限内一直没答。提示词没写出去,确定没投递,`code` 同选项被拒。
51
+ */
52
+ export class AcpExecutorOptionTimeoutError extends AcpExecutorError {
53
+ constructor(option: "model" | "reasoning level", value: string) {
54
+ super(
55
+ "provider-rejected",
56
+ `The agent did not answer the ${option} "${value}" change in time. This turn was not sent.`,
57
+ );
58
+ this.name = "AcpExecutorOptionTimeoutError";
59
+ }
60
+ }
61
+
62
+ /** 选项写入还在等应答时这一轮被停止。只在执行器内部流转,由发送方照停止收口。 */
63
+ export class AcpOptionWriteStoppedError extends Error {
64
+ constructor() {
65
+ super("option write stopped");
66
+ this.name = "AcpOptionWriteStoppedError";
67
+ }
68
+ }
69
+
70
+ /** JSON-RPC 错误或 Error 上给人看的那一段;`data` 是字符串时一并带上(grok 把原因放在那里)。 */
71
+ function acpErrorDetail(cause: unknown): string | undefined {
72
+ if (typeof cause !== "object" || cause === null) return undefined;
73
+ const message = (cause as { readonly message?: unknown }).message;
74
+ const data = (cause as { readonly data?: unknown }).data;
75
+ const parts = [message, data].filter(
76
+ (part): part is string => typeof part === "string" && part.trim().length > 0,
77
+ );
78
+ return parts.length === 0 ? undefined : parts.join(": ");
79
+ }
80
+
81
+ export class AcpExecutorNotStartedError extends AcpExecutorError {
82
+ constructor(message = "ACP session has not been started") {
83
+ super("not-started", message);
84
+ this.name = "AcpExecutorNotStartedError";
85
+ }
86
+ }
87
+
88
+ export class AcpExecutorCancelTimeoutError extends AcpExecutorError {
89
+ constructor(message = "Timed out waiting for session/prompt to finish after cancellation") {
90
+ super("cancel-timeout", message);
91
+ this.name = "AcpExecutorCancelTimeoutError";
92
+ }
93
+ }
94
+
95
+ export class AcpExecutorRequestError extends AcpExecutorError {
96
+ readonly method: string;
97
+
98
+ constructor(method: string, message: string) {
99
+ super("request-failed", message);
100
+ this.name = "AcpExecutorRequestError";
101
+ this.method = method;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * 连接为什么关了。只有 `input-ended`(对端的输出到头:agent 退出或关了 stdout)算 agent 退出;
107
+ * `inbound-failed` 是本端处理入站帧失败(例如应答序列化不了),`stream-error` 是管道自己报错,
108
+ * `closed` 是本端主动关。
109
+ */
110
+ export type AcpConnectionCloseReason = "input-ended" | "inbound-failed" | "stream-error" | "closed";
111
+
112
+ export class AcpConnectionClosedError extends Error {
113
+ readonly reason: AcpConnectionCloseReason;
114
+
115
+ constructor(
116
+ message = "ACP connection closed",
117
+ options?: { readonly cause?: unknown; readonly reason?: AcpConnectionCloseReason },
118
+ ) {
119
+ super(message, options?.cause === undefined ? undefined : { cause: options.cause });
120
+ this.name = "AcpConnectionClosedError";
121
+ this.reason = options?.reason ?? "closed";
122
+ }
123
+ }
124
+
125
+ /**
126
+ * 会话还没建起来连接就断了(agent 启动期退出):错误里附上 agent 自己 stderr 的末尾。
127
+ * 别的错误、或 stderr 是空的,原样返回。仍是 `AcpConnectionClosedError`,按类型判的调用方不受影响。
128
+ */
129
+ export async function withStartupStderr(
130
+ error: unknown,
131
+ stderrTail: (() => string | Promise<string>) | undefined,
132
+ ): Promise<unknown> {
133
+ if (!(error instanceof AcpConnectionClosedError) || stderrTail === undefined) return error;
134
+ const tail = await stderrTail();
135
+ if (tail.length === 0) return error;
136
+ return new AcpConnectionClosedError(`${error.message}\nAgent stderr (last lines):\n${tail}`, {
137
+ cause: error,
138
+ reason: error.reason,
139
+ });
140
+ }
141
+
142
+ /** 中途退出时错误里留的 stderr 上限:宿主时间线只留失败原话的前 1,000 字,原因在最后几行。 */
143
+ const AGENT_EXIT_STDERR_MAX_CHARS = 800;
144
+ /** 输出断了之后等退出码的上限:子进程关了输出却还活着时不能一直等。 */
145
+ const AGENT_EXIT_SETTLE_MS = 500;
146
+
147
+ /**
148
+ * 会话建立之后 agent 进程退出(或关了输出)。`exitCode` 为 undefined 表示等不到退出码。
149
+ * 仍是 `AcpConnectionClosedError`,按类型判的调用方不受影响。
150
+ */
151
+ export class AcpAgentExitedError extends AcpConnectionClosedError {
152
+ readonly exitCode: number | null | undefined;
153
+
154
+ constructor(message: string, exitCode: number | null | undefined, cause: unknown) {
155
+ super(message, { cause, reason: "input-ended" });
156
+ this.name = "AcpAgentExitedError";
157
+ this.exitCode = exitCode;
158
+ }
159
+ }
160
+
161
+ const settledExitCode = async (
162
+ exited: Promise<number | null> | undefined,
163
+ ): Promise<number | null | undefined> => {
164
+ if (exited === undefined) return undefined;
165
+ let timer: ReturnType<typeof setTimeout> | undefined;
166
+ try {
167
+ return await Promise.race([
168
+ exited.catch(() => undefined),
169
+ new Promise<undefined>((resolve) => {
170
+ timer = setTimeout(() => resolve(undefined), AGENT_EXIT_SETTLE_MS);
171
+ }),
172
+ ]);
173
+ } finally {
174
+ clearTimeout(timer);
175
+ }
176
+ };
177
+
178
+ /**
179
+ * 会话中途连接断了:给用户看的原话写成 agent 退出了、退出码多少、它 stderr 的最后几行。
180
+ * `stderrTail` 必须已脱敏(`nodeStreamsFromHandle` 交出的就是),这里不再处理文字。
181
+ */
182
+ export async function describeAgentExit(input: {
183
+ readonly cause: unknown;
184
+ readonly exited: Promise<number | null> | undefined;
185
+ readonly stderrTail: (() => string | Promise<string>) | undefined;
186
+ }): Promise<AcpAgentExitedError> {
187
+ const [exitCode, tail] = await Promise.all([
188
+ settledExitCode(input.exited),
189
+ input.stderrTail === undefined
190
+ ? ""
191
+ : Promise.resolve()
192
+ .then(input.stderrTail)
193
+ .catch(() => ""),
194
+ ]);
195
+ const head =
196
+ exitCode === undefined
197
+ ? "The agent closed its connection."
198
+ : exitCode === null
199
+ ? "The agent process exited without an exit code."
200
+ : `The agent process exited with code ${exitCode}.`;
201
+ const excerpt = lastStderrTail(tail.trim(), AGENT_EXIT_STDERR_MAX_CHARS);
202
+ return new AcpAgentExitedError(
203
+ excerpt.length === 0 ? head : `${head}\nAgent stderr (last lines):\n${excerpt}`,
204
+ exitCode,
205
+ input.cause,
206
+ );
207
+ }
@@ -0,0 +1,91 @@
1
+ import type { ExecutorEvent } from "./types.ts";
2
+
3
+ type Subscriber = {
4
+ readonly queue: ExecutorEvent[];
5
+ wake: (() => void) | undefined;
6
+ closed: boolean;
7
+ };
8
+
9
+ /**
10
+ * 无界事件扇出。与现有 `Queue.unbounded` / `PubSub.unbounded` 一样不限内存。
11
+ *
12
+ * 有界会把入站通道堵住,而取消应答 / 审批请求可能正是解除等待的条件;
13
+ * 审批和生命周期事件也不能丢。文本增量合并是以后的优化,不在这一刀。
14
+ */
15
+ export class UnboundedEventStream {
16
+ private readonly subscribers = new Set<Subscriber>();
17
+ private closed = false;
18
+
19
+ publish(event: ExecutorEvent): void {
20
+ if (this.closed) {
21
+ return;
22
+ }
23
+ for (const subscriber of this.subscribers) {
24
+ if (subscriber.closed) {
25
+ continue;
26
+ }
27
+ subscriber.queue.push(event);
28
+ const wake = subscriber.wake;
29
+ if (wake) {
30
+ subscriber.wake = undefined;
31
+ wake();
32
+ }
33
+ }
34
+ }
35
+
36
+ close(): void {
37
+ if (this.closed) {
38
+ return;
39
+ }
40
+ this.closed = true;
41
+ for (const subscriber of this.subscribers) {
42
+ subscriber.closed = true;
43
+ const wake = subscriber.wake;
44
+ if (wake) {
45
+ subscriber.wake = undefined;
46
+ wake();
47
+ }
48
+ }
49
+ }
50
+
51
+ subscribe(): AsyncIterable<ExecutorEvent> {
52
+ const subscriber: Subscriber = {
53
+ queue: [],
54
+ wake: undefined,
55
+ closed: this.closed,
56
+ };
57
+ this.subscribers.add(subscriber);
58
+ const iterators = this;
59
+ return {
60
+ [Symbol.asyncIterator](): AsyncIterator<ExecutorEvent> {
61
+ return {
62
+ async next() {
63
+ while (true) {
64
+ const buffered = subscriber.queue.shift();
65
+ if (buffered !== undefined) {
66
+ return { value: buffered, done: false };
67
+ }
68
+ if (subscriber.closed || iterators.closed) {
69
+ iterators.subscribers.delete(subscriber);
70
+ return { value: undefined, done: true };
71
+ }
72
+ await new Promise<void>((resolve) => {
73
+ subscriber.wake = resolve;
74
+ });
75
+ }
76
+ },
77
+ async return() {
78
+ subscriber.closed = true;
79
+ iterators.subscribers.delete(subscriber);
80
+ const wake = subscriber.wake;
81
+ if (wake) {
82
+ subscriber.wake = undefined;
83
+ wake();
84
+ }
85
+ return { value: undefined, done: true };
86
+ },
87
+ };
88
+ },
89
+ };
90
+ }
91
+ }
@@ -0,0 +1,341 @@
1
+ /**
2
+ * 从 `AcpCoreRuntimeEvents.ts` 搬来。零 Effect。
3
+ */
4
+ import {
5
+ decideToolCallUpdateEmission,
6
+ mergeToolCallState,
7
+ type AcpPermissionRequest,
8
+ type AcpPlanUpdate,
9
+ type AcpToolCallEmitDecision,
10
+ type AcpToolCallState,
11
+ } from "./runtime-model.ts";
12
+ import { canonicalItemTypeFromAcpToolKind } from "./tool-presentation.ts";
13
+ import type { AcpRequestStatement } from "./permission-statement.ts";
14
+ import type {
15
+ AcpApprovalDecision,
16
+ AcpApprovalOption,
17
+ AcpCanonicalRequestType,
18
+ AcpEventStamp,
19
+ AcpFileChange,
20
+ ExecutorEvent,
21
+ } from "./types.ts";
22
+
23
+ export function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonicalRequestType {
24
+ switch (kind) {
25
+ case "execute":
26
+ return "exec_command_approval";
27
+ case "read":
28
+ return "file_read_approval";
29
+ case "edit":
30
+ case "delete":
31
+ case "move":
32
+ return "file_change_approval";
33
+ case "fetch":
34
+ return "web_fetch_approval";
35
+ case "search":
36
+ return "web_search_approval";
37
+ default:
38
+ return "dynamic_tool_call";
39
+ }
40
+ }
41
+
42
+ export function fileChangesFromAcpPermission(
43
+ permissionRequest: AcpPermissionRequest,
44
+ ): ReadonlyArray<AcpFileChange> | undefined {
45
+ const content = permissionRequest.toolCall?.data["content"];
46
+ const changes = Array.isArray(content)
47
+ ? content.flatMap((entry) => {
48
+ if (entry === null || typeof entry !== "object") {
49
+ return [];
50
+ }
51
+ const block = entry as Record<string, unknown>;
52
+ if (
53
+ block["type"] !== "diff" ||
54
+ typeof block["path"] !== "string" ||
55
+ typeof block["newText"] !== "string"
56
+ ) {
57
+ return [];
58
+ }
59
+ const oldText = typeof block["oldText"] === "string" ? block["oldText"] : undefined;
60
+ return [
61
+ {
62
+ path: block["path"],
63
+ changeKind: oldText === undefined ? ("add" as const) : ("modify" as const),
64
+ content: {
65
+ kind: "replace" as const,
66
+ ...(oldText !== undefined ? { oldText } : {}),
67
+ newText: block["newText"],
68
+ },
69
+ },
70
+ ];
71
+ })
72
+ : [];
73
+ if (changes.length > 0) {
74
+ return changes;
75
+ }
76
+
77
+ if (canonicalRequestTypeFromAcpKind(permissionRequest.kind) !== "file_change_approval") {
78
+ return undefined;
79
+ }
80
+ const locations = permissionRequest.toolCall?.data["locations"];
81
+ const paths = Array.isArray(locations)
82
+ ? locations.flatMap((entry) => {
83
+ const path = (entry as Record<string, unknown> | null)?.["path"];
84
+ return typeof path === "string" && path.trim().length > 0 ? [path] : [];
85
+ })
86
+ : [];
87
+ return paths.length > 0
88
+ ? paths.map((path) => ({ path, omitted: "unavailable" as const }))
89
+ : undefined;
90
+ }
91
+
92
+ function runtimeItemStatusFromAcpToolStatus(
93
+ status: AcpToolCallState["status"],
94
+ ): "inProgress" | "completed" | "failed" | undefined {
95
+ switch (status) {
96
+ case "pending":
97
+ case "inProgress":
98
+ return "inProgress";
99
+ case "completed":
100
+ return "completed";
101
+ case "failed":
102
+ return "failed";
103
+ default:
104
+ return undefined;
105
+ }
106
+ }
107
+
108
+ export function makeAcpRequestOpenedEvent(input: {
109
+ readonly stamp: AcpEventStamp;
110
+ readonly provider: string;
111
+ readonly threadId: string;
112
+ readonly turnId: string | undefined;
113
+ readonly requestId: string;
114
+ readonly permissionRequest: AcpPermissionRequest;
115
+ readonly detail: string | undefined;
116
+ readonly args: unknown;
117
+ readonly statement?: AcpRequestStatement;
118
+ readonly options?: ReadonlyArray<AcpApprovalOption>;
119
+ readonly fileChanges: ReadonlyArray<AcpFileChange> | undefined;
120
+ readonly source: string;
121
+ readonly method: string;
122
+ readonly rawPayload: unknown;
123
+ }): ExecutorEvent {
124
+ const requestType = canonicalRequestTypeFromAcpKind(input.permissionRequest.kind);
125
+ const toolName =
126
+ requestType === "dynamic_tool_call" ? input.permissionRequest.toolCall?.title : undefined;
127
+ return {
128
+ type: "request.opened",
129
+ ...input.stamp,
130
+ provider: input.provider,
131
+ threadId: input.threadId,
132
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
133
+ requestId: input.requestId,
134
+ payload: {
135
+ requestType,
136
+ ...(input.detail ? { detail: input.detail } : {}),
137
+ ...(toolName ? { toolName } : {}),
138
+ args: input.args,
139
+ ...(input.statement !== undefined ? { statement: input.statement } : {}),
140
+ ...(input.options ? { options: input.options } : {}),
141
+ ...(input.fileChanges ? { fileChanges: input.fileChanges } : {}),
142
+ declineReasonRelay: "queued",
143
+ },
144
+ raw: {
145
+ source: input.source,
146
+ method: input.method,
147
+ payload: input.rawPayload,
148
+ },
149
+ };
150
+ }
151
+
152
+ export function makeAcpRequestResolvedEvent(input: {
153
+ readonly stamp: AcpEventStamp;
154
+ readonly provider: string;
155
+ readonly threadId: string;
156
+ readonly turnId: string | undefined;
157
+ readonly requestId: string;
158
+ readonly permissionRequest: AcpPermissionRequest;
159
+ readonly decision: AcpApprovalDecision;
160
+ readonly reason?: string | undefined;
161
+ }): ExecutorEvent {
162
+ return {
163
+ type: "request.resolved",
164
+ ...input.stamp,
165
+ provider: input.provider,
166
+ threadId: input.threadId,
167
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
168
+ requestId: input.requestId,
169
+ payload: {
170
+ requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),
171
+ decision: input.decision,
172
+ ...(input.reason ? { reason: input.reason } : {}),
173
+ },
174
+ };
175
+ }
176
+
177
+ export function makeAcpPlanUpdatedEvent(input: {
178
+ readonly stamp: AcpEventStamp;
179
+ readonly provider: string;
180
+ readonly threadId: string;
181
+ readonly turnId: string | undefined;
182
+ readonly payload: AcpPlanUpdate;
183
+ readonly source: string;
184
+ readonly method: string;
185
+ readonly rawPayload: unknown;
186
+ }): ExecutorEvent {
187
+ return {
188
+ type: "turn.plan.updated",
189
+ ...input.stamp,
190
+ provider: input.provider,
191
+ threadId: input.threadId,
192
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
193
+ payload: input.payload,
194
+ raw: {
195
+ source: input.source,
196
+ method: input.method,
197
+ payload: input.rawPayload,
198
+ },
199
+ };
200
+ }
201
+
202
+ export function makeAcpToolCallEvent(input: {
203
+ readonly stamp: AcpEventStamp;
204
+ readonly provider: string;
205
+ readonly threadId: string;
206
+ readonly turnId: string | undefined;
207
+ readonly toolCall: AcpToolCallState;
208
+ readonly rawPayload: unknown;
209
+ }): ExecutorEvent {
210
+ const runtimeStatus = runtimeItemStatusFromAcpToolStatus(input.toolCall.status);
211
+ const { data } = input.toolCall;
212
+ return {
213
+ type:
214
+ input.toolCall.status === "completed" || input.toolCall.status === "failed"
215
+ ? "item.completed"
216
+ : "item.updated",
217
+ ...input.stamp,
218
+ provider: input.provider,
219
+ threadId: input.threadId,
220
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
221
+ itemId: input.toolCall.toolCallId,
222
+ payload: {
223
+ itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind),
224
+ ...(runtimeStatus ? { status: runtimeStatus } : {}),
225
+ ...(input.toolCall.title ? { title: input.toolCall.title } : {}),
226
+ ...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),
227
+ ...(Object.keys(data).length > 0 ? { data } : {}),
228
+ },
229
+ raw: {
230
+ source: "acp.jsonrpc",
231
+ method: "session/update",
232
+ payload: input.rawPayload,
233
+ },
234
+ };
235
+ }
236
+
237
+ export function makeAcpAssistantItemEvent(input: {
238
+ readonly stamp: AcpEventStamp;
239
+ readonly provider: string;
240
+ readonly threadId: string;
241
+ readonly turnId: string | undefined;
242
+ readonly itemId: string;
243
+ readonly lifecycle: "item.started" | "item.completed";
244
+ }): ExecutorEvent {
245
+ return {
246
+ type: input.lifecycle,
247
+ ...input.stamp,
248
+ provider: input.provider,
249
+ threadId: input.threadId,
250
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
251
+ itemId: input.itemId,
252
+ payload: {
253
+ itemType: "assistant_message",
254
+ status: input.lifecycle === "item.completed" ? "completed" : "inProgress",
255
+ },
256
+ };
257
+ }
258
+
259
+ export function makeAcpContentDeltaEvent(input: {
260
+ readonly stamp: AcpEventStamp;
261
+ readonly provider: string;
262
+ readonly threadId: string;
263
+ readonly turnId: string | undefined;
264
+ readonly itemId?: string;
265
+ readonly text: string;
266
+ readonly streamKind?: "assistant_text" | "reasoning_text";
267
+ readonly rawPayload: unknown;
268
+ }): ExecutorEvent {
269
+ return {
270
+ type: "content.delta",
271
+ ...input.stamp,
272
+ provider: input.provider,
273
+ threadId: input.threadId,
274
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
275
+ ...(input.itemId ? { itemId: input.itemId } : {}),
276
+ payload: {
277
+ streamKind: input.streamKind ?? "assistant_text",
278
+ delta: input.text,
279
+ },
280
+ raw: {
281
+ source: "acp.jsonrpc",
282
+ method: "session/update",
283
+ payload: input.rawPayload,
284
+ },
285
+ };
286
+ }
287
+
288
+ export type AcpToolCallTrackedState = {
289
+ readonly state: AcpToolCallState;
290
+ readonly lastEmittedDetailLength: number | undefined;
291
+ readonly skippedSinceEmit: number;
292
+ /** 第一次见到这条调用时所在的轮。 */
293
+ readonly turnId: string | undefined;
294
+ /** 第一次进入运行态的时刻;通知里没有可靠的开始时刻,取收到那一刻,之后不改。 */
295
+ readonly startedAtMs: number | undefined;
296
+ /** 通知里最近一次给出的 `title` 原文。`state.title` 是加工过的展示标题,认命令不能用它。 */
297
+ readonly rawTitle: string | undefined;
298
+ };
299
+
300
+ /**
301
+ * 终态从这张表去掉。不改事件本身。`seen` 是这条通知带来的、状态里没有的事实;只在第一次进入
302
+ * 运行态时调用 `nowMs`。
303
+ */
304
+ export function retainToolCallUpdate(
305
+ toolCalls: Map<string, AcpToolCallTrackedState>,
306
+ next: AcpToolCallState,
307
+ seen: {
308
+ readonly turnId: string | undefined;
309
+ readonly rawTitle: unknown;
310
+ readonly nowMs: () => number;
311
+ },
312
+ ): {
313
+ readonly nextToolCall: AcpToolCallState;
314
+ readonly decision: AcpToolCallEmitDecision;
315
+ } {
316
+ const tracked = toolCalls.get(next.toolCallId);
317
+ const previous = tracked?.state;
318
+ const nextToolCall = mergeToolCallState(previous, next);
319
+ const decision = decideToolCallUpdateEmission({
320
+ previous,
321
+ next: nextToolCall,
322
+ lastEmittedDetailLength: tracked?.lastEmittedDetailLength,
323
+ skippedSinceEmit: tracked?.skippedSinceEmit ?? 0,
324
+ });
325
+ if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
326
+ toolCalls.delete(nextToolCall.toolCallId);
327
+ } else {
328
+ toolCalls.set(nextToolCall.toolCallId, {
329
+ state: nextToolCall,
330
+ lastEmittedDetailLength: decision.emit
331
+ ? nextToolCall.detail?.length
332
+ : tracked?.lastEmittedDetailLength,
333
+ skippedSinceEmit: decision.skippedSinceEmit,
334
+ turnId: tracked === undefined ? seen.turnId : tracked.turnId,
335
+ startedAtMs:
336
+ tracked?.startedAtMs ?? (nextToolCall.status === "inProgress" ? seen.nowMs() : undefined),
337
+ rawTitle: typeof seen.rawTitle === "string" ? seen.rawTitle : tracked?.rawTitle,
338
+ });
339
+ }
340
+ return { nextToolCall, decision };
341
+ }