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,598 @@
1
+ /**
2
+ * 从 `AcpRuntimeModel.ts` 搬来的解析函数。`waitForSessionLoadReplayIdle` 绑 Effect,这一刀不搬。
3
+ */
4
+ import type { SessionNotification } from "./protocol.ts";
5
+
6
+ import { findConfigOptionEntry } from "./config-options.ts";
7
+ import { isRecord, readAcpText } from "./util.ts";
8
+ import { makeToolCallState, type AcpToolCallState } from "./tool-call-state.ts";
9
+
10
+ export { decideToolCallUpdateEmission, mergeToolCallState } from "./tool-call-state.ts";
11
+ export type { AcpToolCallEmitDecision, AcpToolCallState } from "./tool-call-state.ts";
12
+
13
+ function normalizePlanStepStatus(raw: unknown): "pending" | "inProgress" | "completed" {
14
+ switch (raw) {
15
+ case "completed":
16
+ return "completed";
17
+ case "in_progress":
18
+ case "inProgress":
19
+ return "inProgress";
20
+ default:
21
+ return "pending";
22
+ }
23
+ }
24
+
25
+ interface AcpSessionMode {
26
+ readonly id: string;
27
+ readonly name: string;
28
+ readonly description?: string;
29
+ }
30
+
31
+ export interface AcpSessionModeState {
32
+ readonly currentModeId: string;
33
+ readonly availableModes: ReadonlyArray<AcpSessionMode>;
34
+ }
35
+
36
+ export interface AcpAvailableCommand {
37
+ readonly name: string;
38
+ readonly description?: string;
39
+ readonly inputHint?: string;
40
+ }
41
+
42
+ export interface AcpPlanUpdate {
43
+ readonly explanation?: string | null;
44
+ readonly plan: ReadonlyArray<{
45
+ readonly step: string;
46
+ readonly status: "pending" | "inProgress" | "completed";
47
+ }>;
48
+ }
49
+
50
+ export interface AcpPermissionRequest {
51
+ readonly kind: string | "unknown";
52
+ readonly detail?: string;
53
+ readonly toolCall?: AcpToolCallState;
54
+ }
55
+
56
+ export type AcpParsedSessionEvent =
57
+ | {
58
+ readonly _tag: "ModeChanged";
59
+ readonly modeId: string;
60
+ }
61
+ | {
62
+ readonly _tag: "AssistantItemStarted";
63
+ readonly itemId: string;
64
+ }
65
+ | {
66
+ readonly _tag: "AssistantItemCompleted";
67
+ readonly itemId: string;
68
+ }
69
+ | {
70
+ readonly _tag: "PlanUpdated";
71
+ readonly payload: AcpPlanUpdate;
72
+ readonly rawPayload: unknown;
73
+ }
74
+ | {
75
+ readonly _tag: "ToolCallUpdated";
76
+ readonly toolCall: AcpToolCallState;
77
+ readonly rawPayload: unknown;
78
+ }
79
+ | {
80
+ readonly _tag: "ContextWindowUpdated";
81
+ readonly usedTokens: number;
82
+ readonly maxTokens: number;
83
+ }
84
+ | {
85
+ readonly _tag: "ContentDelta";
86
+ readonly itemId?: string;
87
+ readonly text: string;
88
+ /** 缺省当正式回答。思考块必须标 `reasoning_text`,否则会混进 assistant 段。 */
89
+ readonly streamKind: "assistant_text" | "reasoning_text";
90
+ readonly rawPayload: unknown;
91
+ }
92
+ | {
93
+ readonly _tag: "AssistantContentBlock";
94
+ readonly content: Record<string, unknown>;
95
+ readonly rawPayload: unknown;
96
+ }
97
+ | {
98
+ readonly _tag: "CompactionUpdated";
99
+ readonly compactionId: string;
100
+ /** agent 自报的生命周期词,原样带上(ACP 允许它之外的字符串)。 */
101
+ readonly status: string;
102
+ /**
103
+ * 摘要的补丁语义:缺席 = 不动,`null` 或空数组 = 清掉(这里都归成 `null`),
104
+ * 有值 = 整份替换。
105
+ */
106
+ readonly summary: string | null | undefined;
107
+ readonly error: string | undefined;
108
+ }
109
+ | {
110
+ readonly _tag: "CompactionSummaryChunk";
111
+ readonly compactionId: string;
112
+ readonly text: string;
113
+ };
114
+
115
+ export type AcpSessionSetupResponse = {
116
+ readonly sessionId?: string;
117
+ readonly modes?: {
118
+ readonly currentModeId: string;
119
+ readonly availableModes: ReadonlyArray<{
120
+ readonly id: string;
121
+ readonly name: string;
122
+ readonly description?: string | null;
123
+ }>;
124
+ } | null;
125
+ readonly configOptions?: ReadonlyArray<AcpSessionConfigOption> | null;
126
+ readonly models?: unknown;
127
+ };
128
+
129
+ export type AcpSessionConfigOption = {
130
+ readonly id: string;
131
+ readonly category?: string | null;
132
+ readonly type?: string;
133
+ readonly currentValue?: unknown;
134
+ readonly options?: ReadonlyArray<
135
+ { readonly value: string } | { readonly options: ReadonlyArray<{ readonly value: string }> }
136
+ >;
137
+ };
138
+
139
+ function isSessionModelState(value: unknown): value is {
140
+ readonly currentModelId: string;
141
+ readonly availableModels: ReadonlyArray<Record<string, unknown>>;
142
+ } {
143
+ if (!isRecord(value) || typeof value["currentModelId"] !== "string") {
144
+ return false;
145
+ }
146
+ if (!Array.isArray(value["availableModels"])) {
147
+ return false;
148
+ }
149
+ return value["availableModels"].every(
150
+ (model) =>
151
+ isRecord(model) &&
152
+ typeof model["modelId"] === "string" &&
153
+ typeof model["name"] === "string" &&
154
+ (model["description"] === undefined ||
155
+ model["description"] === null ||
156
+ typeof model["description"] === "string"),
157
+ );
158
+ }
159
+
160
+ function isSessionModeState(value: unknown): value is {
161
+ readonly currentModeId: string;
162
+ readonly availableModes: ReadonlyArray<Record<string, unknown>>;
163
+ } {
164
+ if (!isRecord(value) || typeof value["currentModeId"] !== "string") {
165
+ return false;
166
+ }
167
+ if (!Array.isArray(value["availableModes"])) {
168
+ return false;
169
+ }
170
+ return value["availableModes"].every(
171
+ (mode) =>
172
+ isRecord(mode) &&
173
+ typeof mode["id"] === "string" &&
174
+ typeof mode["name"] === "string" &&
175
+ (mode["description"] === undefined || typeof mode["description"] === "string"),
176
+ );
177
+ }
178
+
179
+ export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
180
+ const configOptions = sessionResponse.configOptions;
181
+ if (!configOptions) return undefined;
182
+ for (const opt of configOptions) {
183
+ if (opt.category === "model" && opt.id.trim().length > 0) {
184
+ return opt.id.trim();
185
+ }
186
+ }
187
+ // category 只是界面提示、可以不报;没有标成 model 的,就认 id 正是 `model` 的那个下拉项。
188
+ return configOptions.find((opt) => opt.id.trim() === "model" && opt.type === "select")
189
+ ? "model"
190
+ : undefined;
191
+ }
192
+
193
+ export function findSessionConfigOption(
194
+ configOptions: ReadonlyArray<AcpSessionConfigOption> | null | undefined,
195
+ configId: string,
196
+ ): AcpSessionConfigOption | undefined {
197
+ return findConfigOptionEntry(configOptions, configId) as AcpSessionConfigOption | undefined;
198
+ }
199
+
200
+ export function collectSessionConfigOptionValues(
201
+ configOption: AcpSessionConfigOption,
202
+ ): ReadonlyArray<string> {
203
+ if (configOption.type !== "select" || !configOption.options) {
204
+ return [];
205
+ }
206
+ return configOption.options.flatMap((entry) =>
207
+ "value" in entry ? [entry.value] : entry.options.map((option) => option.value),
208
+ );
209
+ }
210
+
211
+ /** `models`(UNSTABLE)里报的型号 id,即 `session/set_model` 肯收的那些值。 */
212
+ export function collectSessionModelIds(models: unknown): ReadonlyArray<string> {
213
+ if (!isRecord(models) || !Array.isArray(models["availableModels"])) {
214
+ return [];
215
+ }
216
+ return models["availableModels"].flatMap((model) =>
217
+ isRecord(model) && typeof model["modelId"] === "string" ? [model["modelId"]] : [],
218
+ );
219
+ }
220
+
221
+ /** 请求的型号在手报的目录里对应哪一个取值;规则与 plugin-api 的 `matchCatalogModel` 是同一个函数。 */
222
+ export { matchCatalogModel as matchAdvertisedModelValue } from "./_private/ycodium-executor-common/catalogModel.ts";
223
+
224
+ export function parseSessionModeState(
225
+ sessionResponse: AcpSessionSetupResponse,
226
+ ): AcpSessionModeState | undefined {
227
+ const modes = sessionResponse.modes;
228
+ if (!modes) return undefined;
229
+ const currentModeId = modes.currentModeId.trim();
230
+ if (!currentModeId) {
231
+ return undefined;
232
+ }
233
+ const availableModes: Array<AcpSessionMode> = [];
234
+ for (const mode of modes.availableModes) {
235
+ const id = mode.id.trim();
236
+ const name = mode.name.trim();
237
+ if (!id || !name) {
238
+ continue;
239
+ }
240
+ const description = mode.description?.trim() || undefined;
241
+ availableModes.push(
242
+ description !== undefined
243
+ ? ({ id, name, description } satisfies AcpSessionMode)
244
+ : ({ id, name } satisfies AcpSessionMode),
245
+ );
246
+ }
247
+ if (availableModes.length === 0) {
248
+ return undefined;
249
+ }
250
+ return {
251
+ currentModeId,
252
+ availableModes,
253
+ };
254
+ }
255
+
256
+ /**
257
+ * ACP 宣告的命令 → 插件 API 的斜杠命令形状(`ExecutorSlashCommand`:`input.hint` 是参数提示)。
258
+ * 各 ACP 插件在 `onAvailableCommands` 里用它,经 `host.reportSessionInventory` 报给宿主。
259
+ */
260
+ export function acpCommandsToSlashCommands(
261
+ commands: ReadonlyArray<AcpAvailableCommand>,
262
+ ): ReadonlyArray<{
263
+ readonly name: string;
264
+ readonly description?: string;
265
+ readonly input?: { readonly hint: string };
266
+ }> {
267
+ return commands.map((command) => ({
268
+ name: command.name,
269
+ ...(command.description === undefined ? {} : { description: command.description }),
270
+ ...(command.inputHint === undefined ? {} : { input: { hint: command.inputHint } }),
271
+ }));
272
+ }
273
+
274
+ export function parseAvailableCommandsUpdate(
275
+ params: SessionNotification | { readonly update: Record<string, unknown> },
276
+ ): ReadonlyArray<AcpAvailableCommand> | undefined {
277
+ const update = params.update as Record<string, unknown>;
278
+ if (update["sessionUpdate"] !== "available_commands_update") {
279
+ return undefined;
280
+ }
281
+ const availableCommands = update["availableCommands"];
282
+ if (!Array.isArray(availableCommands)) {
283
+ return [];
284
+ }
285
+ const commands: Array<AcpAvailableCommand> = [];
286
+ for (const command of availableCommands) {
287
+ if (!isRecord(command)) {
288
+ continue;
289
+ }
290
+ const name = typeof command["name"] === "string" ? command["name"].trim() : "";
291
+ if (!name) {
292
+ continue;
293
+ }
294
+ const description =
295
+ typeof command["description"] === "string"
296
+ ? command["description"].trim() || undefined
297
+ : undefined;
298
+ const input = isRecord(command["input"]) ? command["input"] : undefined;
299
+ const inputHint =
300
+ typeof input?.["hint"] === "string" ? input["hint"].trim() || undefined : undefined;
301
+ commands.push({
302
+ name,
303
+ ...(description ? { description } : {}),
304
+ ...(inputHint ? { inputHint } : {}),
305
+ });
306
+ }
307
+ return commands;
308
+ }
309
+
310
+ /**
311
+ * `request_permission.toolCall` 是 `ToolCallUpdate`:只带 `toolCallId` 合法,意思是「前面
312
+ * 通告过的那条」。`known` 是执行器按该 id 从 `session/update` 记下的状态与原始标题。
313
+ * 补全在 ACP 原始字段层做:请求里给了的字段整个用请求的,没给的才沿用已通告的;补全后
314
+ * 的字段只过一次 `makeToolCallState`,命令、标题、详情都由它统一派生。分开合并原始参数和
315
+ * 它的展示缓存,会让请求换掉 `rawInput` 之后旧命令还留在审批详情里。
316
+ */
317
+ export function parsePermissionRequest(
318
+ params: {
319
+ readonly toolCall: {
320
+ readonly toolCallId: string;
321
+ readonly title?: string | null;
322
+ readonly kind?: string | null;
323
+ readonly status?: string | null;
324
+ readonly rawInput?: unknown;
325
+ readonly rawOutput?: unknown;
326
+ readonly content?: unknown;
327
+ readonly locations?: unknown;
328
+ };
329
+ },
330
+ known?: { readonly state: AcpToolCallState; readonly rawTitle: string | undefined },
331
+ ): AcpPermissionRequest {
332
+ const request = params.toolCall;
333
+ const earlier = known?.state.data;
334
+ const toolCall = makeToolCallState(
335
+ {
336
+ toolCallId: request.toolCallId,
337
+ name: earlier?.["name"],
338
+ title: request.title ?? known?.rawTitle,
339
+ kind: request.kind ?? earlier?.["kind"],
340
+ status: request.status ?? known?.state.status,
341
+ rawInput: request.rawInput !== undefined ? request.rawInput : earlier?.["rawInput"],
342
+ rawOutput: request.rawOutput !== undefined ? request.rawOutput : earlier?.["rawOutput"],
343
+ content: request.content !== undefined ? request.content : earlier?.["content"],
344
+ locations: request.locations !== undefined ? request.locations : earlier?.["locations"],
345
+ },
346
+ { fallbackStatus: "pending" },
347
+ );
348
+ const kind = toolCall?.kind ?? "unknown";
349
+ const content = toolCall?.data["content"];
350
+ const firstText = Array.isArray(content)
351
+ ? content.flatMap((entry) => {
352
+ if (!isRecord(entry) || entry["type"] !== "content" || !isRecord(entry["content"]))
353
+ return [];
354
+ const block = entry["content"];
355
+ return block["type"] === "text" && typeof block["text"] === "string" && block["text"].trim()
356
+ ? [block["text"]]
357
+ : [];
358
+ })[0]
359
+ : undefined;
360
+ const originalTitle = (request.title ?? known?.rawTitle)?.trim() || undefined;
361
+ const detail = toolCall?.command ?? firstText ?? originalTitle;
362
+ return {
363
+ kind,
364
+ ...(detail ? { detail } : {}),
365
+ ...(toolCall ? { toolCall } : {}),
366
+ };
367
+ }
368
+
369
+ export function sessionUpdateIsReplay(params: { readonly _meta?: unknown }): boolean {
370
+ const meta = params._meta;
371
+ return isRecord(meta) && meta["isReplay"] === true;
372
+ }
373
+
374
+ export function syntheticLoadSessionResponseFromInitialize(initializeResult: {
375
+ readonly _meta?: unknown;
376
+ }): AcpSessionSetupResponse {
377
+ const meta = initializeResult._meta;
378
+ const modelState = isRecord(meta) ? meta["modelState"] : undefined;
379
+ const modeState = isRecord(meta) ? meta["modeState"] : undefined;
380
+ const models = isSessionModelState(modelState) ? modelState : undefined;
381
+ const modes = isSessionModeState(modeState) ? modeState : undefined;
382
+
383
+ return {
384
+ ...(models ? { models } : {}),
385
+ ...(modes
386
+ ? {
387
+ modes: {
388
+ currentModeId: modes.currentModeId,
389
+ availableModes: modes.availableModes.map((mode) => ({
390
+ id: String(mode["id"]),
391
+ name: String(mode["name"]),
392
+ ...(typeof mode["description"] === "string"
393
+ ? { description: mode["description"] }
394
+ : {}),
395
+ })),
396
+ },
397
+ }
398
+ : {}),
399
+ _meta: {
400
+ ycodiumSessionLoadReady: "replay_idle",
401
+ },
402
+ } as AcpSessionSetupResponse & { readonly _meta: { readonly ycodiumSessionLoadReady: string } };
403
+ }
404
+
405
+ function boundToolCallRawPayload(
406
+ params: SessionNotification,
407
+ update: Record<string, unknown>,
408
+ toolCall: AcpToolCallState,
409
+ ): unknown {
410
+ const boundedContent = toolCall.data["content"];
411
+ const boundedRawOutput = toolCall.data["rawOutput"];
412
+ const contentBounded = update["content"] !== undefined && boundedContent !== update["content"];
413
+ const rawOutputBounded =
414
+ update["rawOutput"] !== undefined && boundedRawOutput !== update["rawOutput"];
415
+ if (!contentBounded && !rawOutputBounded) {
416
+ return params;
417
+ }
418
+ return {
419
+ ...params,
420
+ update: {
421
+ ...update,
422
+ ...(contentBounded ? { content: boundedContent } : {}),
423
+ ...(rawOutputBounded ? { rawOutput: boundedRawOutput } : {}),
424
+ },
425
+ };
426
+ }
427
+
428
+ /** 内容块里的文本拼成一段;没有文本块返回 undefined。 */
429
+ function textFromContentBlocks(blocks: ReadonlyArray<unknown>): string | undefined {
430
+ const parts = blocks.flatMap((block) =>
431
+ isRecord(block) && block["type"] === "text" && typeof block["text"] === "string"
432
+ ? [block["text"]]
433
+ : [],
434
+ );
435
+ const joined = parts.join("");
436
+ return joined.trim().length > 0 ? joined : undefined;
437
+ }
438
+
439
+ export function parseSessionUpdateEvent(params: SessionNotification): {
440
+ readonly modeId?: string;
441
+ readonly events: ReadonlyArray<AcpParsedSessionEvent>;
442
+ } {
443
+ const upd = params.update as unknown as Record<string, unknown>;
444
+ const events: Array<AcpParsedSessionEvent> = [];
445
+ let modeId: string | undefined;
446
+ const kind = upd["sessionUpdate"];
447
+
448
+ switch (kind) {
449
+ case "current_mode_update": {
450
+ modeId = readAcpText(upd, "currentModeId");
451
+ if (modeId) {
452
+ events.push({
453
+ _tag: "ModeChanged",
454
+ modeId,
455
+ });
456
+ }
457
+ break;
458
+ }
459
+ case "plan": {
460
+ const entries = Array.isArray(upd["entries"]) ? upd["entries"] : [];
461
+ const plan = entries.map((entry, index) => ({
462
+ step: readAcpText(entry, "content") ?? `Step ${index + 1}`,
463
+ status: normalizePlanStepStatus(isRecord(entry) ? entry["status"] : undefined),
464
+ }));
465
+ if (plan.length > 0) {
466
+ events.push({
467
+ _tag: "PlanUpdated",
468
+ payload: {
469
+ plan,
470
+ },
471
+ rawPayload: params,
472
+ });
473
+ }
474
+ break;
475
+ }
476
+ case "tool_call":
477
+ case "tool_call_update": {
478
+ const toolCall = makeToolCallState(
479
+ {
480
+ toolCallId: upd["toolCallId"],
481
+ name: upd["name"],
482
+ title: typeof upd["title"] === "string" ? upd["title"] : undefined,
483
+ kind: upd["kind"],
484
+ status: upd["status"],
485
+ rawInput: upd["rawInput"],
486
+ rawOutput: upd["rawOutput"],
487
+ content: upd["content"],
488
+ locations: upd["locations"],
489
+ },
490
+ kind === "tool_call" ? { fallbackStatus: "pending" } : undefined,
491
+ );
492
+ if (toolCall) {
493
+ events.push({
494
+ _tag: "ToolCallUpdated",
495
+ toolCall,
496
+ rawPayload: boundToolCallRawPayload(params, upd, toolCall),
497
+ });
498
+ }
499
+ break;
500
+ }
501
+ case "agent_message_chunk":
502
+ case "agent_thought_chunk": {
503
+ const content = isRecord(upd["content"]) ? upd["content"] : undefined;
504
+ const contentType = content?.["type"];
505
+ const streamKind =
506
+ kind === "agent_thought_chunk" ? ("reasoning_text" as const) : ("assistant_text" as const);
507
+ if (contentType === "text") {
508
+ const text = typeof content?.["text"] === "string" ? content["text"] : "";
509
+ if (text.length > 0) {
510
+ events.push({
511
+ _tag: "ContentDelta",
512
+ text,
513
+ streamKind,
514
+ rawPayload: params,
515
+ });
516
+ }
517
+ break;
518
+ }
519
+ // 思考块没有非文本形态可投影;正式回答的非音频块留给附件路径。
520
+ if (streamKind === "assistant_text" && content && contentType !== "audio") {
521
+ events.push({
522
+ _tag: "AssistantContentBlock",
523
+ content,
524
+ rawPayload: params,
525
+ });
526
+ }
527
+ break;
528
+ }
529
+ case "usage_update": {
530
+ const used = upd["used"];
531
+ const size = upd["size"];
532
+ if (
533
+ typeof used === "number" &&
534
+ Number.isSafeInteger(used) &&
535
+ used >= 0 &&
536
+ typeof size === "number" &&
537
+ Number.isSafeInteger(size) &&
538
+ size > 0
539
+ ) {
540
+ events.push({ _tag: "ContextWindowUpdated", usedTokens: used, maxTokens: size });
541
+ }
542
+ break;
543
+ }
544
+ case "compaction_update": {
545
+ const compactionId = readAcpText(upd, "compactionId");
546
+ const status = readAcpText(upd, "status");
547
+ if (compactionId === undefined || status === undefined) break;
548
+ const rawSummary = upd["summary"];
549
+ events.push({
550
+ _tag: "CompactionUpdated",
551
+ compactionId,
552
+ status,
553
+ summary:
554
+ rawSummary === undefined
555
+ ? undefined
556
+ : Array.isArray(rawSummary)
557
+ ? (textFromContentBlocks(rawSummary) ?? null)
558
+ : null,
559
+ error: readAcpText(upd, "error"),
560
+ });
561
+ break;
562
+ }
563
+ case "compaction_summary_chunk": {
564
+ const compactionId = readAcpText(upd, "compactionId");
565
+ const content = isRecord(upd["content"]) ? upd["content"] : undefined;
566
+ const text = content?.["type"] === "text" ? content["text"] : undefined;
567
+ if (compactionId === undefined || typeof text !== "string" || text.length === 0) break;
568
+ events.push({ _tag: "CompactionSummaryChunk", compactionId, text });
569
+ break;
570
+ }
571
+ default:
572
+ break;
573
+ }
574
+
575
+ return { ...(modeId !== undefined ? { modeId } : {}), events };
576
+ }
577
+
578
+ export function filterMcpServersByAgentCapabilities<T extends { readonly type?: string }>(
579
+ mcpServers: ReadonlyArray<T>,
580
+ agentCapabilities:
581
+ | { readonly mcpCapabilities?: { readonly http?: boolean; readonly sse?: boolean } }
582
+ | null
583
+ | undefined,
584
+ ): ReadonlyArray<T> {
585
+ return mcpServers.filter((server) => {
586
+ if (!("type" in server) || server.type === undefined) {
587
+ return true;
588
+ }
589
+ switch (server.type) {
590
+ case "http":
591
+ return agentCapabilities?.mcpCapabilities?.http === true;
592
+ case "sse":
593
+ return agentCapabilities?.mcpCapabilities?.sse === true;
594
+ default:
595
+ return true;
596
+ }
597
+ });
598
+ }
@@ -0,0 +1,82 @@
1
+ import type { AcpExecutor } from "./executor.ts";
2
+ import type { AcpSessionClose } from "./session-registry.ts";
3
+
4
+ // 转发拒绝即已结束、不可恢复:只让第一次收尾报出来,否则这条会话永远停不掉。
5
+ const reportedForwardingFailures = new WeakSet<Promise<void>>();
6
+
7
+ /**
8
+ * 三步必须全部尝试;任一步失败就以带步骤名的错误拒绝,调用方据此保留归属、允许再停。
9
+ * 转发可先拒绝,但拒绝仍须交回关闭调用方,且只交一次。
10
+ */
11
+ export async function cleanupAcpSession(input: {
12
+ readonly executor: Pick<AcpExecutor, "dispose">;
13
+ readonly stopProcess: () => Promise<void>;
14
+ readonly forwarding: Promise<void>;
15
+ readonly processExit?: AcpSessionClose;
16
+ }): Promise<void> {
17
+ const failures: Error[] = [];
18
+ const forwarding = input.forwarding.catch((cause: unknown) => {
19
+ if (reportedForwardingFailures.has(input.forwarding)) return;
20
+ reportedForwardingFailures.add(input.forwarding);
21
+ failures.push(new Error(`forwarding failed: ${String(cause)}`, { cause }));
22
+ });
23
+ for (const [step, cleanup] of [
24
+ ["executor.dispose", () => input.executor.dispose(input.processExit?.exitCode)],
25
+ [
26
+ "stopProcess",
27
+ () => (input.processExit?.hasExited() ? Promise.resolve() : input.stopProcess()),
28
+ ],
29
+ ["forwarding", () => forwarding],
30
+ ] as const) {
31
+ try {
32
+ await cleanup();
33
+ } catch (cause) {
34
+ failures.push(new Error(`${step} failed: ${String(cause)}`, { cause }));
35
+ }
36
+ }
37
+ if (failures.length > 0) {
38
+ throw new AggregateError(failures, failures.map((error) => error.message).join("; "));
39
+ }
40
+ }
41
+
42
+ /** 启动失败时的收尾:原启动错误优先,由调用方照抛;清理失败只记 warn。返回清理是否成功。 */
43
+ export async function cleanupAcpStartup(
44
+ input: Parameters<typeof cleanupAcpSession>[0] & {
45
+ readonly log: { readonly warn: (message: string, context?: Record<string, unknown>) => void };
46
+ readonly threadId: string;
47
+ },
48
+ ): Promise<boolean> {
49
+ try {
50
+ await cleanupAcpSession(input);
51
+ return true;
52
+ } catch (cleanupError) {
53
+ input.log.warn("ACP session startup cleanup failed", {
54
+ threadId: input.threadId,
55
+ error: String(cleanupError),
56
+ });
57
+ return false;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 关闭任务:进行中共用一趟,成功后保留结果,失败后释放以便再调重试。
63
+ * 先登记再执行:`run` 同步前缀里重入的调用也只拿到这一趟。
64
+ */
65
+ export function createRetryableClose(run: () => Promise<void>): () => Promise<void> {
66
+ let task: Promise<void> | undefined;
67
+ return () => {
68
+ if (task) return task;
69
+ const done = Promise.withResolvers<void>();
70
+ const current = done.promise;
71
+ task = current;
72
+ void current.catch(() => {
73
+ if (task === current) task = undefined;
74
+ });
75
+ try {
76
+ run().then(done.resolve, done.reject);
77
+ } catch (cause) {
78
+ done.reject(cause);
79
+ }
80
+ return current;
81
+ };
82
+ }