ycodium-acp-executor 0.2.5634 → 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 (244) hide show
  1. package/README.md +2 -1
  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/usageFields.d.ts +5 -0
  27. package/dist/_private/ycodium-jsonl-stream/usageFields.js +11 -0
  28. package/dist/_private/ycodium-workspace-path/directoryScope.d.ts +5 -0
  29. package/dist/_private/ycodium-workspace-path/directoryScope.js +28 -0
  30. package/dist/_private/ycodium-workspace-path/workspacePath.d.ts +19 -0
  31. package/dist/_private/ycodium-workspace-path/workspacePath.js +90 -0
  32. package/dist/adapter-support.d.ts.map +1 -1
  33. package/dist/adapter-support.js.map +1 -1
  34. package/dist/apply-effort.d.ts.map +1 -1
  35. package/dist/apply-effort.js.map +1 -1
  36. package/dist/approvals.d.ts.map +1 -1
  37. package/dist/approvals.js.map +1 -1
  38. package/dist/artifacts.d.ts.map +1 -1
  39. package/dist/artifacts.js.map +1 -1
  40. package/dist/card-defaults.d.ts.map +1 -1
  41. package/dist/card-defaults.js.map +1 -1
  42. package/dist/config-option-wiring.d.ts.map +1 -1
  43. package/dist/config-option-wiring.js.map +1 -1
  44. package/dist/config-options.d.ts.map +1 -1
  45. package/dist/config-options.js.map +1 -1
  46. package/dist/connection.d.ts.map +1 -1
  47. package/dist/connection.js.map +1 -1
  48. package/dist/errors.d.ts.map +1 -1
  49. package/dist/errors.js.map +1 -1
  50. package/dist/event-stream.d.ts.map +1 -1
  51. package/dist/event-stream.js.map +1 -1
  52. package/dist/events.d.ts.map +1 -1
  53. package/dist/events.js.map +1 -1
  54. package/dist/executor/child-sessions.d.ts.map +1 -1
  55. package/dist/executor/child-sessions.js.map +1 -1
  56. package/dist/executor/lifecycle.d.ts.map +1 -1
  57. package/dist/executor/lifecycle.js.map +1 -1
  58. package/dist/executor/prompt-results.d.ts.map +1 -1
  59. package/dist/executor/prompt-results.js.map +1 -1
  60. package/dist/executor/prompt.d.ts.map +1 -1
  61. package/dist/executor/prompt.js.map +1 -1
  62. package/dist/executor/requests.d.ts.map +1 -1
  63. package/dist/executor/requests.js.map +1 -1
  64. package/dist/executor/runtime.d.ts.map +1 -1
  65. package/dist/executor/runtime.js.map +1 -1
  66. package/dist/executor/session.d.ts.map +1 -1
  67. package/dist/executor/session.js +17 -1
  68. package/dist/executor/session.js.map +1 -1
  69. package/dist/executor/settlement.d.ts.map +1 -1
  70. package/dist/executor/settlement.js.map +1 -1
  71. package/dist/executor/subagent-sessions.d.ts.map +1 -1
  72. package/dist/executor/subagent-sessions.js.map +1 -1
  73. package/dist/executor/support.d.ts.map +1 -1
  74. package/dist/executor/support.js.map +1 -1
  75. package/dist/executor/updates.d.ts.map +1 -1
  76. package/dist/executor/updates.js.map +1 -1
  77. package/dist/executor.d.ts.map +1 -1
  78. package/dist/executor.js.map +1 -1
  79. package/dist/failureCategory.d.ts.map +1 -1
  80. package/dist/failureCategory.js.map +1 -1
  81. package/dist/handshake.d.ts.map +1 -1
  82. package/dist/handshake.js.map +1 -1
  83. package/dist/index.d.ts +1 -1
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +1 -1
  86. package/dist/index.js.map +1 -1
  87. package/dist/instance-kit.d.ts.map +1 -1
  88. package/dist/instance-kit.js.map +1 -1
  89. package/dist/jsonrpc.d.ts.map +1 -1
  90. package/dist/jsonrpc.js.map +1 -1
  91. package/dist/line-buffer.d.ts.map +1 -1
  92. package/dist/line-buffer.js.map +1 -1
  93. package/dist/mcp-servers.d.ts +26 -4
  94. package/dist/mcp-servers.d.ts.map +1 -1
  95. package/dist/mcp-servers.js +25 -4
  96. package/dist/mcp-servers.js.map +1 -1
  97. package/dist/model-selection.d.ts.map +1 -1
  98. package/dist/model-selection.js.map +1 -1
  99. package/dist/model-send.d.ts.map +1 -1
  100. package/dist/model-send.js.map +1 -1
  101. package/dist/mutex.d.ts.map +1 -1
  102. package/dist/mutex.js.map +1 -1
  103. package/dist/native-session-transcript.d.ts.map +1 -1
  104. package/dist/native-session-transcript.js.map +1 -1
  105. package/dist/native-sessions.d.ts.map +1 -1
  106. package/dist/native-sessions.js.map +1 -1
  107. package/dist/openCommands.d.ts.map +1 -1
  108. package/dist/openCommands.js.map +1 -1
  109. package/dist/permission-statement.d.ts.map +1 -1
  110. package/dist/permission-statement.js.map +1 -1
  111. package/dist/probe-process.d.ts.map +1 -1
  112. package/dist/probe-process.js.map +1 -1
  113. package/dist/probe-session.d.ts.map +1 -1
  114. package/dist/probe-session.js.map +1 -1
  115. package/dist/probe.d.ts.map +1 -1
  116. package/dist/probe.js.map +1 -1
  117. package/dist/prompt-dispatch.d.ts.map +1 -1
  118. package/dist/prompt-dispatch.js.map +1 -1
  119. package/dist/protocol-log.d.ts.map +1 -1
  120. package/dist/protocol-log.js.map +1 -1
  121. package/dist/protocol.d.ts.map +1 -1
  122. package/dist/protocol.js.map +1 -1
  123. package/dist/refreshDeadline.d.ts.map +1 -1
  124. package/dist/refreshDeadline.js.map +1 -1
  125. package/dist/runtime-mode.d.ts.map +1 -1
  126. package/dist/runtime-mode.js.map +1 -1
  127. package/dist/runtime-model.d.ts.map +1 -1
  128. package/dist/runtime-model.js.map +1 -1
  129. package/dist/session-cleanup.d.ts.map +1 -1
  130. package/dist/session-cleanup.js.map +1 -1
  131. package/dist/session-registry.d.ts.map +1 -1
  132. package/dist/session-registry.js.map +1 -1
  133. package/dist/session-update.d.ts.map +1 -1
  134. package/dist/session-update.js.map +1 -1
  135. package/dist/sessionProcess.d.ts.map +1 -1
  136. package/dist/sessionProcess.js.map +1 -1
  137. package/dist/source/_private/ycodium-executor-common/catalogModel.ts +40 -0
  138. package/dist/source/_private/ycodium-executor-common/eventTypes.ts +97 -0
  139. package/dist/source/_private/ycodium-executor-common/modelSelection.ts +24 -0
  140. package/dist/source/_private/ycodium-executor-common/nodeStreams.ts +212 -0
  141. package/dist/source/_private/ycodium-executor-common/raceAbort.ts +25 -0
  142. package/dist/source/_private/ycodium-executor-common/reasoningLevelFallback.ts +28 -0
  143. package/dist/source/_private/ycodium-executor-common/stderrTail.ts +27 -0
  144. package/dist/source/_private/ycodium-executor-common/toolPresentation.ts +268 -0
  145. package/dist/source/_private/ycodium-jsonl-stream/appendedJsonl.ts +222 -0
  146. package/dist/source/_private/ycodium-jsonl-stream/claudeSessions.ts +263 -0
  147. package/dist/source/_private/ycodium-jsonl-stream/codexSessions.ts +254 -0
  148. package/dist/source/_private/ycodium-jsonl-stream/history.ts +492 -0
  149. package/dist/source/_private/ycodium-jsonl-stream/historyErrors.ts +6 -0
  150. package/dist/source/_private/ycodium-jsonl-stream/historyFile.ts +139 -0
  151. package/dist/source/_private/ycodium-jsonl-stream/historyRecord.ts +180 -0
  152. package/dist/source/_private/ycodium-jsonl-stream/historyWaiting.ts +140 -0
  153. package/dist/source/_private/ycodium-jsonl-stream/jsonObjectLine.ts +15 -0
  154. package/dist/source/_private/ycodium-jsonl-stream/jsonlStream.ts +650 -0
  155. package/dist/source/_private/ycodium-jsonl-stream/scanCache.ts +163 -0
  156. package/dist/source/_private/ycodium-jsonl-stream/sessionDirectory.ts +39 -0
  157. package/dist/source/_private/ycodium-jsonl-stream/sessionTranscript.ts +136 -0
  158. package/dist/source/_private/ycodium-jsonl-stream/usageFields.ts +13 -0
  159. package/dist/source/_private/ycodium-workspace-path/directoryScope.ts +34 -0
  160. package/dist/source/_private/ycodium-workspace-path/workspacePath.ts +110 -0
  161. package/dist/source/adapter-support.ts +115 -0
  162. package/dist/source/apply-effort.ts +66 -0
  163. package/dist/source/approvals.ts +94 -0
  164. package/dist/source/artifacts.ts +88 -0
  165. package/dist/source/card-defaults.ts +25 -0
  166. package/dist/source/config-option-wiring.ts +119 -0
  167. package/dist/source/config-options.ts +270 -0
  168. package/dist/source/connection.ts +553 -0
  169. package/dist/source/errors.ts +207 -0
  170. package/dist/source/event-stream.ts +91 -0
  171. package/dist/source/events.ts +341 -0
  172. package/dist/source/executor/child-sessions.ts +87 -0
  173. package/dist/source/executor/lifecycle.ts +282 -0
  174. package/dist/source/executor/prompt-results.ts +123 -0
  175. package/dist/source/executor/prompt.ts +606 -0
  176. package/dist/source/executor/requests.ts +323 -0
  177. package/dist/source/executor/runtime.ts +137 -0
  178. package/dist/source/executor/session.ts +553 -0
  179. package/dist/source/executor/settlement.ts +92 -0
  180. package/dist/source/executor/subagent-sessions.ts +183 -0
  181. package/dist/source/executor/support.ts +129 -0
  182. package/dist/source/executor/updates.ts +427 -0
  183. package/dist/source/executor.ts +537 -0
  184. package/dist/source/failureCategory.ts +74 -0
  185. package/dist/source/handshake.ts +66 -0
  186. package/dist/source/index.ts +210 -0
  187. package/dist/source/instance-kit.ts +478 -0
  188. package/dist/source/jsonrpc.ts +59 -0
  189. package/dist/source/line-buffer.ts +54 -0
  190. package/dist/source/mcp-servers.ts +83 -0
  191. package/dist/source/model-selection.ts +138 -0
  192. package/dist/source/model-send.ts +80 -0
  193. package/dist/source/mutex.ts +47 -0
  194. package/dist/source/native-session-transcript.ts +167 -0
  195. package/dist/source/native-sessions.ts +271 -0
  196. package/dist/source/openCommands.ts +39 -0
  197. package/dist/source/permission-statement.ts +49 -0
  198. package/dist/source/probe-process.ts +95 -0
  199. package/dist/source/probe-session.ts +81 -0
  200. package/dist/source/probe.ts +261 -0
  201. package/dist/source/prompt-dispatch.ts +42 -0
  202. package/dist/source/protocol-log.ts +143 -0
  203. package/dist/source/protocol.ts +36 -0
  204. package/dist/source/refreshDeadline.ts +2 -0
  205. package/dist/source/runtime-mode.ts +125 -0
  206. package/dist/source/runtime-model.ts +598 -0
  207. package/dist/source/session-cleanup.ts +82 -0
  208. package/dist/source/session-registry.ts +62 -0
  209. package/dist/source/session-update.ts +88 -0
  210. package/dist/source/sessionProcess.ts +29 -0
  211. package/dist/source/start-abort.ts +19 -0
  212. package/dist/source/thread-operations.ts +145 -0
  213. package/dist/source/tool-call-state.ts +322 -0
  214. package/dist/source/tool-presentation.ts +20 -0
  215. package/dist/source/tool-subagents.ts +491 -0
  216. package/dist/source/turn-usage.ts +78 -0
  217. package/dist/source/types.ts +146 -0
  218. package/dist/source/user-input-pending.ts +31 -0
  219. package/dist/source/util.ts +38 -0
  220. package/dist/source/vendor-hooks.ts +394 -0
  221. package/dist/start-abort.d.ts.map +1 -1
  222. package/dist/start-abort.js.map +1 -1
  223. package/dist/thread-operations.d.ts.map +1 -1
  224. package/dist/thread-operations.js.map +1 -1
  225. package/dist/tool-call-state.d.ts.map +1 -1
  226. package/dist/tool-call-state.js.map +1 -1
  227. package/dist/tool-presentation.d.ts.map +1 -1
  228. package/dist/tool-presentation.js.map +1 -1
  229. package/dist/tool-subagents.d.ts +1 -0
  230. package/dist/tool-subagents.d.ts.map +1 -1
  231. package/dist/tool-subagents.js +2 -0
  232. package/dist/tool-subagents.js.map +1 -1
  233. package/dist/turn-usage.d.ts.map +1 -1
  234. package/dist/turn-usage.js.map +1 -1
  235. package/dist/types.d.ts.map +1 -1
  236. package/dist/types.js.map +1 -1
  237. package/dist/user-input-pending.d.ts.map +1 -1
  238. package/dist/user-input-pending.js.map +1 -1
  239. package/dist/util.d.ts.map +1 -1
  240. package/dist/util.js.map +1 -1
  241. package/dist/vendor-hooks.d.ts +9 -0
  242. package/dist/vendor-hooks.d.ts.map +1 -1
  243. package/dist/vendor-hooks.js.map +1 -1
  244. package/package.json +5 -2
@@ -0,0 +1,62 @@
1
+ export type AcpSessionClose = {
2
+ readonly exitCode: number | null | undefined;
3
+ readonly hasExited: () => boolean;
4
+ };
5
+
6
+ /**
7
+ * 关闭期间保留归属;所有关闭入口必须复用同一任务,成功后才能删记录。
8
+ * 失败时记录仍归原会话,且只在表里还是同一条时复位关闭任务,允许再停。
9
+ */
10
+ export function createAcpSessionRegistry<T extends { closing?: Promise<void> }>(
11
+ threads: Map<string, T>,
12
+ stopBooked: (booked: T, close: AcpSessionClose) => Promise<void>,
13
+ log?: { warn(message: string, context?: Record<string, unknown>): void },
14
+ ) {
15
+ const exits = new WeakMap<T, number | null>();
16
+ const requireThread = (threadId: string): T => {
17
+ const booked = threads.get(threadId);
18
+ if (!booked) throw new Error(`unknown thread ${threadId}`);
19
+ if (booked.closing) throw new Error(`thread ${threadId} is closing`);
20
+ return booked;
21
+ };
22
+
23
+ const stopSession = (threadId: string, booked = threads.get(threadId)): Promise<void> => {
24
+ if (!booked) return Promise.resolve();
25
+ // 原因固定在认领任务时;是否还需杀进程则在执行到那一步时重读。
26
+ const close = { exitCode: exits.get(booked), hasExited: () => exits.has(booked) };
27
+ // 先认领再执行,关闭回调即使重入也只能拿到这一次任务。
28
+ booked.closing ??= Promise.resolve()
29
+ .then(() => stopBooked(booked, close))
30
+ .then(() => {
31
+ if (threads.get(threadId) === booked) threads.delete(threadId);
32
+ })
33
+ .catch((cause: unknown) => {
34
+ if (threads.get(threadId) === booked) delete booked.closing;
35
+ throw cause;
36
+ });
37
+ return booked.closing;
38
+ };
39
+
40
+ const stopAll = (): Promise<void> =>
41
+ Promise.all([...threads].map(([threadId, booked]) => stopSession(threadId, booked))).then(
42
+ () => undefined,
43
+ );
44
+
45
+ const registerSession = (
46
+ threadId: string,
47
+ booked: T & { handle: { exited: Promise<number | null> } },
48
+ ): void => {
49
+ threads.set(threadId, booked);
50
+ void booked.handle.exited
51
+ .then(async (exitCode) => {
52
+ exits.set(booked, exitCode);
53
+ await stopSession(threadId, booked);
54
+ })
55
+ .catch((cause: unknown) => {
56
+ // 自动收尾失败仍保留归属,显式 stop / dispose 可以重试。
57
+ log?.warn("ACP process exit cleanup failed", { threadId, error: String(cause) });
58
+ });
59
+ };
60
+
61
+ return { requireThread, registerSession, stopSession, stopAll };
62
+ }
@@ -0,0 +1,88 @@
1
+ import type { SessionNotification } from "@agentclientprotocol/sdk";
2
+
3
+ import { isRecord } from "./jsonrpc.ts";
4
+
5
+ /**
6
+ * `session/update` 信封:够路由就行,update 里的内容一概不校验。
7
+ * 只校验路由所需的 `sessionId` 与 `update.sessionUpdate`。
8
+ */
9
+ export type SessionUpdateEnvelope = {
10
+ readonly sessionId: string;
11
+ readonly update: {
12
+ readonly sessionUpdate: string;
13
+ readonly [key: string]: unknown;
14
+ };
15
+ readonly [key: string]: unknown;
16
+ };
17
+
18
+ export type SessionUpdateDecode =
19
+ | { readonly status: "decoded"; readonly params: SessionNotification }
20
+ | { readonly status: "raw"; readonly params: SessionNotification }
21
+ | { readonly status: "dropped" };
22
+
23
+ /**
24
+ * 已知的 `session/update` 变体名。
25
+ *
26
+ * **这是一份手抄名单,SDK 没有把它导出成运行时值**(`zSessionUpdate` 不在包的公开
27
+ * 导出里,`types.gen.d.ts` 只有类型)。抄一份就有分叉风险:SDK 升级新增变体时这里
28
+ * 不更新,那个变体会走 `raw` 而不是 `decoded`——不丢消息,但少一层形状校验。
29
+ *
30
+ * `session-update.test.ts` 有一条对拍:数量与 SDK 类型文件里的 `sessionUpdate: "…"`
31
+ * 字面量个数必须相等,升级后对不上就红。
32
+ */
33
+ export const KNOWN_SESSION_UPDATES = new Set<string>([
34
+ "user_message_chunk",
35
+ "agent_message_chunk",
36
+ "agent_thought_chunk",
37
+ "tool_call",
38
+ "tool_call_update",
39
+ "plan",
40
+ "plan_update",
41
+ "plan_removed",
42
+ "available_commands_update",
43
+ "current_mode_update",
44
+ "config_option_update",
45
+ "session_info_update",
46
+ "usage_update",
47
+ "compaction_update",
48
+ "compaction_summary_chunk",
49
+ ]);
50
+
51
+ export function isSessionUpdateEnvelope(payload: unknown): payload is SessionUpdateEnvelope {
52
+ if (!isRecord(payload) || typeof payload["sessionId"] !== "string") {
53
+ return false;
54
+ }
55
+ const update = payload["update"];
56
+ return isRecord(update) && typeof update["sessionUpdate"] === "string";
57
+ }
58
+
59
+ function hasKnownVariantShape(update: Record<string, unknown>): boolean {
60
+ const kind = update["sessionUpdate"];
61
+ if (typeof kind !== "string" || !KNOWN_SESSION_UPDATES.has(kind)) {
62
+ return false;
63
+ }
64
+ if (
65
+ kind === "user_message_chunk" ||
66
+ kind === "agent_message_chunk" ||
67
+ kind === "agent_thought_chunk"
68
+ ) {
69
+ return isRecord(update["content"]);
70
+ }
71
+ return true;
72
+ }
73
+
74
+ /**
75
+ * 先按已知变体形状解码;失败时信封对得上就原样投递,信封不对才丢。
76
+ *
77
+ * SDK 高层 `onNotification("session/update")` 会 `.parse()` 丢掉未知变体和残缺
78
+ * 已知变体,所以这一步必须在 JSON-RPC 路由层自己做。
79
+ */
80
+ export function decodeSessionUpdate(payload: unknown): SessionUpdateDecode {
81
+ if (!isSessionUpdateEnvelope(payload)) {
82
+ return { status: "dropped" };
83
+ }
84
+ if (hasKnownVariantShape(payload.update)) {
85
+ return { status: "decoded", params: payload as SessionNotification };
86
+ }
87
+ return { status: "raw", params: payload as SessionNotification };
88
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * 用户停下一轮时(D184),宿主要在插件起的根进程和它的后代里认出「说 ACP 的那个进程」。原生程序装的
3
+ * ACP 手(kimi、grok)没有启动器,会话进程就是宿主起的那个:程序与启动参数逐项相同才认。
4
+ * 这里只给这条判定;哪条工具调用算命令、命令的 shell 长什么样,各家形状不同,由插件自己判。
5
+ */
6
+
7
+ const fileName = (path: string) => path.slice(path.lastIndexOf("/") + 1);
8
+ const withoutExe = (name: string) => name.replace(/\.exe$/, "");
9
+
10
+ /**
11
+ * 进程表里的 argv 是不是宿主按 `program` 与 `args` 起的那个进程。`program` 填的是路径就比整条路径,
12
+ * 只是名字就比文件名;Windows 上不分大小写、忽略 `.exe`。
13
+ */
14
+ export function acpNativeSessionProcessMatcher(
15
+ program: string,
16
+ args: ReadonlyArray<string>,
17
+ ): (argv: ReadonlyArray<string>, platform: string) => boolean {
18
+ return (argv, platform) => {
19
+ const normalize = (value: string) =>
20
+ platform === "win32" ? withoutExe(value.replaceAll("\\", "/").toLowerCase()) : value;
21
+ const expected = normalize(program);
22
+ const actual = normalize(argv[0] ?? "");
23
+ const sameProgram = expected.includes("/")
24
+ ? actual === expected
25
+ : fileName(actual) === fileName(expected);
26
+ const rest = argv.slice(1);
27
+ return sameProgram && rest.length === args.length && rest.every((arg, i) => arg === args[i]);
28
+ };
29
+ }
@@ -0,0 +1,19 @@
1
+ export function throwIfStartAborted(signal?: AbortSignal): void {
2
+ if (signal?.aborted) throw new Error("aborted");
3
+ }
4
+
5
+ export async function raceStartAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
6
+ // 调用方可能已经启动工作;取消后迟到的拒绝也必须有人接住。
7
+ void promise.catch(() => undefined);
8
+ throwIfStartAborted(signal);
9
+ if (signal === undefined) return promise;
10
+
11
+ const aborted = Promise.withResolvers<never>();
12
+ const onAbort = () => aborted.reject(new Error("aborted"));
13
+ signal.addEventListener("abort", onAbort, { once: true });
14
+ try {
15
+ return await Promise.race([promise, aborted.promise]);
16
+ } finally {
17
+ signal.removeEventListener("abort", onAbort);
18
+ }
19
+ }
@@ -0,0 +1,145 @@
1
+ // @effect-diagnostics globalDate:off globalTimers:off
2
+ import type { AcpExecutor } from "./executor.ts";
3
+ import { dispatchAcpPrompt } from "./prompt-dispatch.ts";
4
+ import type { AcpRuntimeMode } from "./runtime-mode.ts";
5
+
6
+ /** 会话记录里这层要读写的几项。与 `@ycodium-ai/plugin-api` 的 `ExecutorSession` 同形的那一部分。 */
7
+ export type AcpThreadSession = {
8
+ readonly runtimeMode: AcpRuntimeMode;
9
+ readonly nativeModeId?: string;
10
+ readonly updatedAt: string;
11
+ readonly resumeCursor?: unknown;
12
+ };
13
+
14
+ /** 一个线程上开着的 ACP 会话:会话记录、已发的轮次与执行器。插件可以在上面加自己的字段。 */
15
+ export type AcpBookedThread<Session extends AcpThreadSession> = {
16
+ closing?: Promise<void>;
17
+ session: Session;
18
+ turns: Array<{ id: string; items: ReadonlyArray<unknown> }>;
19
+ executor: AcpExecutor;
20
+ };
21
+
22
+ /** 这一轮要的型号与思考档。档位那一格的 id 各家不同,由插件从宿主的 modelSelection 读出。 */
23
+ export type AcpTurnSelection = {
24
+ readonly requestedModelId?: string;
25
+ readonly requestedEffort?: string;
26
+ };
27
+
28
+ export type AcpSendTurnInput = {
29
+ readonly threadId: string;
30
+ readonly input?: string;
31
+ readonly expectedTurnId?: string;
32
+ readonly modelSelection?: unknown;
33
+ };
34
+
35
+ const yieldTick = (): Promise<void> =>
36
+ new Promise((resolve) => {
37
+ setImmediate(resolve);
38
+ });
39
+
40
+ const nowIso = (): string => new Date().toISOString();
41
+
42
+ /**
43
+ * 会话开起来之后的几项实例操作:发一轮、打断、答审批与提问、切原生档与四档、读线程。
44
+ * 每家都一样的部分在这里;起会话、探测与厂商自己的动作仍在插件里。
45
+ */
46
+ export function createAcpThreadOperations<
47
+ Session extends AcpThreadSession,
48
+ Booked extends AcpBookedThread<Session>,
49
+ >(options: {
50
+ readonly threads: ReadonlyMap<string, Booked>;
51
+ readonly requireThread: (threadId: string) => Booked;
52
+ readonly isDisposed: () => boolean;
53
+ /** 从宿主的 modelSelection 读这一轮的型号与档位;只在用 `sendTurn` 时需要,缺席时不带。 */
54
+ readonly turnSelection?: (modelSelection: unknown) => AcpTurnSelection;
55
+ readonly log: { info(message: string, context?: Record<string, unknown>): void };
56
+ /** 写 prompt 之前的厂商动作(例如先同步权限)。 */
57
+ readonly beforeSendTurn?: (booked: Booked) => void;
58
+ }) {
59
+ const { threads, requireThread } = options;
60
+ return {
61
+ sendTurn: async (input: AcpSendTurnInput, signal?: AbortSignal) => {
62
+ if (options.isDisposed()) throw new Error("instance disposed");
63
+ const booked = requireThread(input.threadId);
64
+ if (signal?.aborted) throw new Error("aborted");
65
+ options.beforeSendTurn?.(booked);
66
+
67
+ const onAbort = (): void => {
68
+ void booked.executor.cancel(input.expectedTurnId).catch(() => undefined);
69
+ };
70
+ signal?.addEventListener("abort", onAbort);
71
+ try {
72
+ const { requestedModelId, requestedEffort } =
73
+ options.turnSelection?.(input.modelSelection) ?? {};
74
+ // 型号与思考档由执行器在发送前于会话内对齐,不重开会话。写进 CLI 的 stdin 就返回(规则 13),
75
+ // 整轮结果走 turn.completed;会话在整轮收尾后才回 idle。
76
+ const turn = await dispatchAcpPrompt(booked.executor, {
77
+ text: input.input ?? "",
78
+ expectedActiveTurnId: input.expectedTurnId,
79
+ ...(requestedModelId === undefined ? {} : { requestedModelId }),
80
+ ...(requestedEffort === undefined ? {} : { requestedEffort }),
81
+ });
82
+ booked.turns.push({ id: turn.turnId, items: [] });
83
+ return {
84
+ threadId: input.threadId,
85
+ turnId: turn.turnId,
86
+ ...(booked.session.resumeCursor === undefined
87
+ ? {}
88
+ : { resumeCursor: booked.session.resumeCursor }),
89
+ };
90
+ } finally {
91
+ signal?.removeEventListener("abort", onAbort);
92
+ }
93
+ },
94
+
95
+ interruptTurn: async (threadId: string, turnId?: string) => {
96
+ const booked = threads.get(threadId);
97
+ if (booked === undefined || booked.closing) return;
98
+ options.log.info("interrupt turn", { threadId, turnId });
99
+ await booked.executor.cancel(turnId);
100
+ await yieldTick();
101
+ },
102
+
103
+ respondToRequest: async (
104
+ threadId: string,
105
+ requestId: string,
106
+ decision: "allow" | "deny",
107
+ reason?: string,
108
+ ) => {
109
+ const booked = requireThread(threadId);
110
+ await booked.executor.respondToRequest(
111
+ requestId,
112
+ decision === "allow" ? "accept" : "decline",
113
+ reason,
114
+ );
115
+ },
116
+
117
+ respondToUserInput: async (threadId: string, requestId: string, answers: unknown) => {
118
+ const booked = requireThread(threadId);
119
+ await booked.executor.respondToUserInput(requestId, answers);
120
+ },
121
+
122
+ /**
123
+ * 切这只手自报的审批档。`nativeModeId` 是它自己报的 id(探测时原样上报的那些),
124
+ * 一路不翻译成宿主四档。
125
+ *
126
+ * 这是 `setRuntimeMode` 做不到的那一半:那个只改插件自己的会话记录,CLI 收不到
127
+ * (`runtime-mode-never-reaches-cli` 记的那族缺陷)。
128
+ */
129
+ setNativeMode: async (threadId: string, nativeModeId: string) => {
130
+ const booked = requireThread(threadId);
131
+ await booked.executor.setNativeMode(nativeModeId);
132
+ booked.session = { ...booked.session, nativeModeId, updatedAt: nowIso() };
133
+ },
134
+
135
+ setRuntimeMode: async (threadId: string, runtimeMode: AcpRuntimeMode) => {
136
+ const booked = requireThread(threadId);
137
+ booked.session = { ...booked.session, runtimeMode, updatedAt: nowIso() };
138
+ },
139
+
140
+ readThread: async (threadId: string) => {
141
+ const booked = requireThread(threadId);
142
+ return { threadId, turns: booked.turns };
143
+ },
144
+ };
145
+ }
@@ -0,0 +1,322 @@
1
+ // ACP 工具调用的状态整理:从会话更新里取出调用、合并后续更新,并决定要不要把这一拍发出去。
2
+ // 会话事件的总解析仍在 runtime-model.ts。
3
+
4
+ import { deriveToolActivityPresentation } from "./_private/ycodium-executor-common/toolPresentation.ts";
5
+
6
+ import { canonicalItemTypeFromAcpToolKind } from "./tool-presentation.ts";
7
+ import { isRecord, readAcpText } from "./util.ts";
8
+
9
+ export interface AcpToolCallState {
10
+ readonly toolCallId: string;
11
+ readonly kind?: string;
12
+ readonly title?: string;
13
+ readonly status?: "pending" | "inProgress" | "completed" | "failed";
14
+ readonly command?: string;
15
+ readonly detail?: string;
16
+ /** `content` 里文本块归一化后的结果(拼接、截断),只算一次,钩子直接用。 */
17
+ readonly contentText?: string;
18
+ readonly data: Record<string, unknown>;
19
+ }
20
+
21
+ function normalizeToolCallStatus(
22
+ raw: unknown,
23
+ fallback?: "pending" | "inProgress" | "completed" | "failed",
24
+ ): "pending" | "inProgress" | "completed" | "failed" | undefined {
25
+ switch (raw) {
26
+ case "pending":
27
+ return "pending";
28
+ case "in_progress":
29
+ case "inProgress":
30
+ return "inProgress";
31
+ case "completed":
32
+ return "completed";
33
+ case "failed":
34
+ return "failed";
35
+ default:
36
+ return fallback;
37
+ }
38
+ }
39
+
40
+ function normalizeCommandValue(value: unknown): string | undefined {
41
+ if (typeof value === "string" && value.trim().length > 0) {
42
+ return value.trim();
43
+ }
44
+ if (!Array.isArray(value)) {
45
+ return undefined;
46
+ }
47
+ const parts: Array<string> = [];
48
+ for (const entry of value) {
49
+ if (typeof entry === "string") {
50
+ const part = entry.trim();
51
+ if (part.length > 0) {
52
+ parts.push(part);
53
+ }
54
+ }
55
+ }
56
+ return parts.length > 0 ? parts.join(" ") : undefined;
57
+ }
58
+
59
+ function extractCommandFromTitle(title: string | undefined): string | undefined {
60
+ if (!title) {
61
+ return undefined;
62
+ }
63
+ const match = /`([^`]+)`/.exec(title);
64
+ return match?.[1]?.trim() || undefined;
65
+ }
66
+
67
+ function extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined {
68
+ if (isRecord(rawInput)) {
69
+ const directCommand = normalizeCommandValue(rawInput["command"]);
70
+ if (directCommand) {
71
+ return directCommand;
72
+ }
73
+ const executable =
74
+ typeof rawInput["executable"] === "string" ? rawInput["executable"].trim() : "";
75
+ const args = normalizeCommandValue(rawInput["args"]);
76
+ if (executable && args) {
77
+ return `${executable} ${args}`;
78
+ }
79
+ if (executable) {
80
+ return executable;
81
+ }
82
+ }
83
+ return extractCommandFromTitle(title);
84
+ }
85
+
86
+ const TOOL_CALL_CONTENT_MAX_CHARS = 8_000;
87
+ const TOOL_CALL_CONTENT_TRUNCATION_MARKER = "[Earlier output truncated]\n\n";
88
+
89
+ /** 超长文本只留末尾 `limit` 个字符并在前面标出被截断。 */
90
+ export function boundTailText(text: string, limit = TOOL_CALL_CONTENT_MAX_CHARS): string {
91
+ if (text.length <= limit) {
92
+ return text;
93
+ }
94
+ const tail = text.slice(text.length - limit);
95
+ return `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${tail}`;
96
+ }
97
+
98
+ const boundToolCallOutputText = (text: string): string => boundTailText(text);
99
+
100
+ const RAW_OUTPUT_TEXT_FIELDS = ["content", "stdout", "stderr", "output"] as const;
101
+
102
+ function boundToolCallRawOutput(rawOutput: unknown): unknown {
103
+ if (!isRecord(rawOutput)) {
104
+ return rawOutput;
105
+ }
106
+ let changed = false;
107
+ const bounded: Record<string, unknown> = { ...rawOutput };
108
+ for (const field of RAW_OUTPUT_TEXT_FIELDS) {
109
+ const value = rawOutput[field];
110
+ if (typeof value === "string" && value.length > TOOL_CALL_CONTENT_MAX_CHARS) {
111
+ bounded[field] = boundToolCallOutputText(value);
112
+ changed = true;
113
+ }
114
+ }
115
+ return changed ? bounded : rawOutput;
116
+ }
117
+
118
+ type ToolCallContentEntry = {
119
+ readonly type: string;
120
+ readonly content?: { readonly type?: string; readonly text?: string };
121
+ readonly [key: string]: unknown;
122
+ };
123
+
124
+ function toolCallContentText(entry: ToolCallContentEntry): string | undefined {
125
+ if (entry.type !== "content" || entry.content?.type !== "text") {
126
+ return undefined;
127
+ }
128
+ return entry.content.text;
129
+ }
130
+
131
+ function extractTextContentFromToolCallContent(content: unknown): {
132
+ readonly text: string | undefined;
133
+ readonly content: ReadonlyArray<ToolCallContentEntry> | undefined;
134
+ } {
135
+ if (!Array.isArray(content)) {
136
+ return { text: undefined, content: undefined };
137
+ }
138
+ const typed = content as ReadonlyArray<ToolCallContentEntry>;
139
+ const chunks: Array<string> = [];
140
+ for (const entry of typed) {
141
+ const text = toolCallContentText(entry)?.trim();
142
+ if (text) {
143
+ chunks.push(text);
144
+ }
145
+ }
146
+ if (chunks.length === 0) {
147
+ return { text: undefined, content: typed };
148
+ }
149
+ const joined = chunks.join("\n");
150
+ if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
151
+ return { text: joined, content: typed };
152
+ }
153
+ const bounded = boundToolCallOutputText(joined);
154
+ const lastContributingTextIndex = typed.reduce(
155
+ (lastIndex, entry, index) => (toolCallContentText(entry)?.trim() ? index : lastIndex),
156
+ -1,
157
+ );
158
+ const boundedContent = typed.flatMap((entry, index) => {
159
+ if (toolCallContentText(entry) === undefined) {
160
+ return [entry];
161
+ }
162
+ if (index !== lastContributingTextIndex) {
163
+ return [];
164
+ }
165
+ return [{ type: "content", content: { type: "text", text: bounded } } as const];
166
+ });
167
+ return { text: bounded, content: boundedContent };
168
+ }
169
+
170
+ function normalizeToolKind(kind: unknown): string | undefined {
171
+ return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
172
+ }
173
+
174
+ export function makeToolCallState(
175
+ input: {
176
+ readonly toolCallId: unknown;
177
+ /** ACP 扩展字段,常只有首条 tool_call 带;落进 `data` 由 `mergeToolCallState` 沿用,后到的覆盖旧的。 */
178
+ readonly name?: unknown;
179
+ readonly title?: string | null | undefined;
180
+ readonly kind?: unknown;
181
+ readonly status?: unknown;
182
+ readonly rawInput?: unknown;
183
+ readonly rawOutput?: unknown;
184
+ readonly content?: unknown;
185
+ readonly locations?: unknown;
186
+ },
187
+ options?: {
188
+ readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
189
+ },
190
+ ): AcpToolCallState | undefined {
191
+ const toolCallId = typeof input.toolCallId === "string" ? input.toolCallId.trim() : "";
192
+ if (!toolCallId) {
193
+ return undefined;
194
+ }
195
+ const title = typeof input.title === "string" ? input.title.trim() || undefined : undefined;
196
+ const command = extractToolCallCommand(input.rawInput, title);
197
+ const extractedContent = extractTextContentFromToolCallContent(input.content);
198
+ const textContent = extractedContent.text;
199
+ const normalizedTitle =
200
+ title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
201
+ ? title
202
+ : undefined;
203
+ const data: Record<string, unknown> = { toolCallId };
204
+ const kind = normalizeToolKind(input.kind);
205
+ if (kind) {
206
+ data["kind"] = kind;
207
+ }
208
+ const name = readAcpText(input, "name");
209
+ if (name) {
210
+ data["name"] = name;
211
+ }
212
+ if (command) {
213
+ data["command"] = command;
214
+ }
215
+ if (input.rawInput !== undefined) {
216
+ data["rawInput"] = input.rawInput;
217
+ }
218
+ if (input.rawOutput !== undefined) {
219
+ data["rawOutput"] = boundToolCallRawOutput(input.rawOutput);
220
+ }
221
+ if (input.content !== undefined) {
222
+ data["content"] = extractedContent.content ?? input.content;
223
+ }
224
+ if (input.locations !== undefined) {
225
+ data["locations"] = input.locations;
226
+ }
227
+ const fallbackDetail = command ?? normalizedTitle ?? textContent;
228
+ const hasPresentationSeed =
229
+ title !== undefined ||
230
+ kind !== undefined ||
231
+ command !== undefined ||
232
+ normalizedTitle !== undefined ||
233
+ textContent !== undefined;
234
+ const presentation = hasPresentationSeed
235
+ ? deriveToolActivityPresentation({
236
+ itemType: canonicalItemTypeFromAcpToolKind(kind),
237
+ title,
238
+ detail: fallbackDetail,
239
+ data,
240
+ fallbackSummary: title ?? "Tool",
241
+ })
242
+ : undefined;
243
+ const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
244
+ return {
245
+ toolCallId,
246
+ ...(kind ? { kind } : {}),
247
+ ...(presentation?.summary ? { title: presentation.summary } : {}),
248
+ ...(status ? { status } : {}),
249
+ ...(command ? { command } : {}),
250
+ ...(presentation?.detail ? { detail: presentation.detail } : {}),
251
+ ...(textContent ? { contentText: textContent } : {}),
252
+ data,
253
+ };
254
+ }
255
+
256
+ export function mergeToolCallState(
257
+ previous: AcpToolCallState | undefined,
258
+ next: AcpToolCallState,
259
+ ): AcpToolCallState {
260
+ const nextKind = typeof next.data["kind"] === "string" ? next.data["kind"] : undefined;
261
+ const kind = nextKind ?? previous?.kind;
262
+ const title = next.title ?? previous?.title;
263
+ const status = next.status ?? previous?.status;
264
+ const command = next.command ?? previous?.command;
265
+ const detail = next.detail ?? previous?.detail;
266
+ // 这一帧带了 content(哪怕是空的)就以它为准;没带才沿用上一帧的文本。
267
+ const contentText = "content" in next.data ? next.contentText : previous?.contentText;
268
+ return {
269
+ toolCallId: next.toolCallId,
270
+ ...(kind ? { kind } : {}),
271
+ ...(title ? { title } : {}),
272
+ ...(status ? { status } : {}),
273
+ ...(command ? { command } : {}),
274
+ ...(detail ? { detail } : {}),
275
+ ...(contentText ? { contentText } : {}),
276
+ data: {
277
+ ...previous?.data,
278
+ ...next.data,
279
+ },
280
+ };
281
+ }
282
+
283
+ const TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS = 256;
284
+ const TOOL_CALL_UPDATE_COALESCE_LIMIT = 10;
285
+
286
+ export interface AcpToolCallEmitDecisionInput {
287
+ readonly previous: AcpToolCallState | undefined;
288
+ readonly next: AcpToolCallState;
289
+ readonly lastEmittedDetailLength: number | undefined;
290
+ readonly skippedSinceEmit: number;
291
+ }
292
+
293
+ export interface AcpToolCallEmitDecision {
294
+ readonly emit: boolean;
295
+ readonly skippedSinceEmit: number;
296
+ }
297
+
298
+ export function decideToolCallUpdateEmission(
299
+ input: AcpToolCallEmitDecisionInput,
300
+ ): AcpToolCallEmitDecision {
301
+ const { previous, next, lastEmittedDetailLength, skippedSinceEmit } = input;
302
+ if (next.status === "completed" || next.status === "failed") {
303
+ return { emit: true, skippedSinceEmit: 0 };
304
+ }
305
+ if (!next.detail) {
306
+ return { emit: false, skippedSinceEmit };
307
+ }
308
+ if (previous === undefined || previous.title !== next.title) {
309
+ return { emit: true, skippedSinceEmit: 0 };
310
+ }
311
+ if (previous.detail === next.detail) {
312
+ return { emit: false, skippedSinceEmit };
313
+ }
314
+ const grewMeaningfully =
315
+ lastEmittedDetailLength === undefined ||
316
+ Math.abs(next.detail.length - lastEmittedDetailLength) >=
317
+ TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
318
+ if (grewMeaningfully || skippedSinceEmit + 1 >= TOOL_CALL_UPDATE_COALESCE_LIMIT) {
319
+ return { emit: true, skippedSinceEmit: 0 };
320
+ }
321
+ return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
322
+ }
@@ -0,0 +1,20 @@
1
+ // ACP 的工具类别到宿主工具生命周期类别的映射;摘要行规则在 ycodium-executor-common/toolPresentation。
2
+ import type { AcpToolLifecycleItemType } from "./types.ts";
3
+
4
+ export function canonicalItemTypeFromAcpToolKind(
5
+ kind: string | undefined,
6
+ ): AcpToolLifecycleItemType {
7
+ switch (kind) {
8
+ case "execute":
9
+ return "command_execution";
10
+ case "edit":
11
+ case "delete":
12
+ case "move":
13
+ return "file_change";
14
+ case "search":
15
+ case "fetch":
16
+ return "web_search";
17
+ default:
18
+ return "dynamic_tool_call";
19
+ }
20
+ }