ycodium-acp-executor 0.2.5634 → 0.2.5854

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 (250) 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 +2 -1
  58. package/dist/executor/lifecycle.js.map +1 -1
  59. package/dist/executor/prompt-results.d.ts.map +1 -1
  60. package/dist/executor/prompt-results.js.map +1 -1
  61. package/dist/executor/prompt.d.ts.map +1 -1
  62. package/dist/executor/prompt.js.map +1 -1
  63. package/dist/executor/requests.d.ts.map +1 -1
  64. package/dist/executor/requests.js.map +1 -1
  65. package/dist/executor/runtime.d.ts.map +1 -1
  66. package/dist/executor/runtime.js.map +1 -1
  67. package/dist/executor/session.d.ts.map +1 -1
  68. package/dist/executor/session.js +17 -1
  69. package/dist/executor/session.js.map +1 -1
  70. package/dist/executor/settlement.d.ts.map +1 -1
  71. package/dist/executor/settlement.js.map +1 -1
  72. package/dist/executor/subagent-sessions.d.ts.map +1 -1
  73. package/dist/executor/subagent-sessions.js.map +1 -1
  74. package/dist/executor/support.d.ts +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 +21 -6
  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 +1 -1
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +1 -1
  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.map +1 -1
  115. package/dist/probe-process.js.map +1 -1
  116. package/dist/probe-session.d.ts.map +1 -1
  117. package/dist/probe-session.js.map +1 -1
  118. package/dist/probe.d.ts.map +1 -1
  119. package/dist/probe.js.map +1 -1
  120. package/dist/prompt-dispatch.d.ts.map +1 -1
  121. package/dist/prompt-dispatch.js.map +1 -1
  122. package/dist/protocol-log.d.ts.map +1 -1
  123. package/dist/protocol-log.js.map +1 -1
  124. package/dist/protocol.d.ts.map +1 -1
  125. package/dist/protocol.js.map +1 -1
  126. package/dist/refreshDeadline.d.ts.map +1 -1
  127. package/dist/refreshDeadline.js.map +1 -1
  128. package/dist/runtime-mode.d.ts.map +1 -1
  129. package/dist/runtime-mode.js.map +1 -1
  130. package/dist/runtime-model.d.ts +2 -2
  131. package/dist/runtime-model.d.ts.map +1 -1
  132. package/dist/runtime-model.js +4 -4
  133. package/dist/runtime-model.js.map +1 -1
  134. package/dist/session-cleanup.d.ts.map +1 -1
  135. package/dist/session-cleanup.js.map +1 -1
  136. package/dist/session-registry.d.ts.map +1 -1
  137. package/dist/session-registry.js.map +1 -1
  138. package/dist/session-update.d.ts.map +1 -1
  139. package/dist/session-update.js.map +1 -1
  140. package/dist/sessionProcess.d.ts.map +1 -1
  141. package/dist/sessionProcess.js.map +1 -1
  142. package/dist/source/_private/ycodium-executor-common/catalogModel.ts +40 -0
  143. package/dist/source/_private/ycodium-executor-common/eventTypes.ts +97 -0
  144. package/dist/source/_private/ycodium-executor-common/modelSelection.ts +24 -0
  145. package/dist/source/_private/ycodium-executor-common/nodeStreams.ts +212 -0
  146. package/dist/source/_private/ycodium-executor-common/raceAbort.ts +25 -0
  147. package/dist/source/_private/ycodium-executor-common/reasoningLevelFallback.ts +28 -0
  148. package/dist/source/_private/ycodium-executor-common/stderrTail.ts +27 -0
  149. package/dist/source/_private/ycodium-executor-common/toolPresentation.ts +268 -0
  150. package/dist/source/_private/ycodium-jsonl-stream/appendedJsonl.ts +222 -0
  151. package/dist/source/_private/ycodium-jsonl-stream/claudeSessions.ts +263 -0
  152. package/dist/source/_private/ycodium-jsonl-stream/codexSessions.ts +254 -0
  153. package/dist/source/_private/ycodium-jsonl-stream/history.ts +492 -0
  154. package/dist/source/_private/ycodium-jsonl-stream/historyErrors.ts +6 -0
  155. package/dist/source/_private/ycodium-jsonl-stream/historyFile.ts +139 -0
  156. package/dist/source/_private/ycodium-jsonl-stream/historyRecord.ts +180 -0
  157. package/dist/source/_private/ycodium-jsonl-stream/historyWaiting.ts +140 -0
  158. package/dist/source/_private/ycodium-jsonl-stream/jsonObjectLine.ts +15 -0
  159. package/dist/source/_private/ycodium-jsonl-stream/jsonlStream.ts +650 -0
  160. package/dist/source/_private/ycodium-jsonl-stream/scanCache.ts +163 -0
  161. package/dist/source/_private/ycodium-jsonl-stream/sessionDirectory.ts +39 -0
  162. package/dist/source/_private/ycodium-jsonl-stream/sessionTranscript.ts +136 -0
  163. package/dist/source/_private/ycodium-jsonl-stream/usageFields.ts +13 -0
  164. package/dist/source/_private/ycodium-workspace-path/directoryScope.ts +34 -0
  165. package/dist/source/_private/ycodium-workspace-path/workspacePath.ts +110 -0
  166. package/dist/source/adapter-support.ts +115 -0
  167. package/dist/source/apply-effort.ts +66 -0
  168. package/dist/source/approvals.ts +94 -0
  169. package/dist/source/artifacts.ts +88 -0
  170. package/dist/source/card-defaults.ts +25 -0
  171. package/dist/source/config-option-wiring.ts +119 -0
  172. package/dist/source/config-options.ts +270 -0
  173. package/dist/source/connection.ts +553 -0
  174. package/dist/source/errors.ts +207 -0
  175. package/dist/source/event-stream.ts +91 -0
  176. package/dist/source/events.ts +341 -0
  177. package/dist/source/executor/child-sessions.ts +87 -0
  178. package/dist/source/executor/lifecycle.ts +283 -0
  179. package/dist/source/executor/prompt-results.ts +123 -0
  180. package/dist/source/executor/prompt.ts +606 -0
  181. package/dist/source/executor/requests.ts +323 -0
  182. package/dist/source/executor/runtime.ts +137 -0
  183. package/dist/source/executor/session.ts +553 -0
  184. package/dist/source/executor/settlement.ts +92 -0
  185. package/dist/source/executor/subagent-sessions.ts +183 -0
  186. package/dist/source/executor/support.ts +129 -0
  187. package/dist/source/executor/updates.ts +446 -0
  188. package/dist/source/executor.ts +537 -0
  189. package/dist/source/failureCategory.ts +74 -0
  190. package/dist/source/handshake.ts +66 -0
  191. package/dist/source/index.ts +210 -0
  192. package/dist/source/instance-kit.ts +478 -0
  193. package/dist/source/jsonrpc.ts +59 -0
  194. package/dist/source/line-buffer.ts +54 -0
  195. package/dist/source/mcp-servers.ts +83 -0
  196. package/dist/source/model-selection.ts +138 -0
  197. package/dist/source/model-send.ts +80 -0
  198. package/dist/source/mutex.ts +47 -0
  199. package/dist/source/native-session-transcript.ts +167 -0
  200. package/dist/source/native-sessions.ts +271 -0
  201. package/dist/source/openCommands.ts +39 -0
  202. package/dist/source/permission-statement.ts +49 -0
  203. package/dist/source/probe-process.ts +95 -0
  204. package/dist/source/probe-session.ts +81 -0
  205. package/dist/source/probe.ts +261 -0
  206. package/dist/source/prompt-dispatch.ts +42 -0
  207. package/dist/source/protocol-log.ts +143 -0
  208. package/dist/source/protocol.ts +36 -0
  209. package/dist/source/refreshDeadline.ts +2 -0
  210. package/dist/source/runtime-mode.ts +125 -0
  211. package/dist/source/runtime-model.ts +598 -0
  212. package/dist/source/session-cleanup.ts +82 -0
  213. package/dist/source/session-registry.ts +62 -0
  214. package/dist/source/session-update.ts +88 -0
  215. package/dist/source/sessionProcess.ts +29 -0
  216. package/dist/source/start-abort.ts +19 -0
  217. package/dist/source/thread-operations.ts +145 -0
  218. package/dist/source/tool-call-state.ts +322 -0
  219. package/dist/source/tool-presentation.ts +20 -0
  220. package/dist/source/tool-subagents.ts +491 -0
  221. package/dist/source/turn-usage.ts +88 -0
  222. package/dist/source/types.ts +146 -0
  223. package/dist/source/user-input-pending.ts +31 -0
  224. package/dist/source/util.ts +38 -0
  225. package/dist/source/vendor-hooks.ts +395 -0
  226. package/dist/start-abort.d.ts.map +1 -1
  227. package/dist/start-abort.js.map +1 -1
  228. package/dist/thread-operations.d.ts.map +1 -1
  229. package/dist/thread-operations.js.map +1 -1
  230. package/dist/tool-call-state.d.ts.map +1 -1
  231. package/dist/tool-call-state.js.map +1 -1
  232. package/dist/tool-presentation.d.ts.map +1 -1
  233. package/dist/tool-presentation.js.map +1 -1
  234. package/dist/tool-subagents.d.ts +1 -0
  235. package/dist/tool-subagents.d.ts.map +1 -1
  236. package/dist/tool-subagents.js +2 -0
  237. package/dist/tool-subagents.js.map +1 -1
  238. package/dist/turn-usage.d.ts.map +1 -1
  239. package/dist/turn-usage.js +12 -1
  240. package/dist/turn-usage.js.map +1 -1
  241. package/dist/types.d.ts.map +1 -1
  242. package/dist/types.js.map +1 -1
  243. package/dist/user-input-pending.d.ts.map +1 -1
  244. package/dist/user-input-pending.js.map +1 -1
  245. package/dist/util.d.ts.map +1 -1
  246. package/dist/util.js.map +1 -1
  247. package/dist/vendor-hooks.d.ts +11 -1
  248. package/dist/vendor-hooks.d.ts.map +1 -1
  249. package/dist/vendor-hooks.js.map +1 -1
  250. package/package.json +5 -2
@@ -0,0 +1,59 @@
1
+ import type { AnyNotification, AnyRequest, AnyResponse } from "@agentclientprotocol/sdk";
2
+
3
+ export function isRecord(value: unknown): value is Record<string, unknown> {
4
+ return typeof value === "object" && value !== null;
5
+ }
6
+
7
+ function isJsonRpcId(value: unknown): value is string | number {
8
+ return typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
9
+ }
10
+
11
+ function isJsonRpcEnvelope(value: unknown): value is Record<string, unknown> {
12
+ return isRecord(value) && value["jsonrpc"] === "2.0";
13
+ }
14
+
15
+ export function isRequestMessage(value: unknown): value is AnyRequest {
16
+ return (
17
+ isJsonRpcEnvelope(value) &&
18
+ "id" in value &&
19
+ typeof value["method"] === "string" &&
20
+ isJsonRpcId(value["id"])
21
+ );
22
+ }
23
+
24
+ export function isResponseMessage(value: unknown): value is AnyResponse {
25
+ if (!isJsonRpcEnvelope(value) || "method" in value) {
26
+ return false;
27
+ }
28
+ if (!("id" in value) || !isJsonRpcId(value["id"])) {
29
+ return false;
30
+ }
31
+ const hasResult = Object.hasOwn(value, "result");
32
+ const hasError = Object.hasOwn(value, "error");
33
+ return hasResult !== hasError;
34
+ }
35
+
36
+ export function isNotificationMessage(value: unknown): value is AnyNotification {
37
+ return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
38
+ }
39
+
40
+ export type JsonRpcErrorShape = {
41
+ readonly code: number;
42
+ readonly message: string;
43
+ readonly data?: unknown;
44
+ };
45
+
46
+ export function readJsonRpcError(value: unknown): JsonRpcErrorShape | undefined {
47
+ if (
48
+ !isRecord(value) ||
49
+ typeof value["code"] !== "number" ||
50
+ typeof value["message"] !== "string"
51
+ ) {
52
+ return undefined;
53
+ }
54
+ return {
55
+ code: value["code"],
56
+ message: value["message"],
57
+ ...(Object.hasOwn(value, "data") ? { data: value["data"] } : {}),
58
+ };
59
+ }
@@ -0,0 +1,54 @@
1
+ const newline = 0x0a;
2
+
3
+ /**
4
+ * Incrementally splits a byte stream into newline-terminated lines.
5
+ *
6
+ * Matches the algorithm in `@agentclientprotocol/sdk` `ndJsonStream` so a
7
+ * single stdio `data` chunk still groups every complete line that arrived
8
+ * together. That grouping is what inbound idle needs; the SDK's readable
9
+ * yields one message per line and awaits between them.
10
+ */
11
+ export class LineBuffer {
12
+ #pending: Uint8Array[] = [];
13
+
14
+ push(chunk: Uint8Array): Uint8Array[] {
15
+ const lines: Uint8Array[] = [];
16
+ let start = 0;
17
+ let newlineIndex = chunk.indexOf(newline, start);
18
+ while (newlineIndex !== -1) {
19
+ lines.push(this.#takeLine(chunk.subarray(start, newlineIndex)));
20
+ start = newlineIndex + 1;
21
+ newlineIndex = chunk.indexOf(newline, start);
22
+ }
23
+ if (start < chunk.byteLength) {
24
+ this.#pending.push(start === 0 ? chunk : new Uint8Array(chunk.subarray(start)));
25
+ }
26
+ return lines;
27
+ }
28
+
29
+ flush(): Uint8Array | undefined {
30
+ if (this.#pending.length === 0) {
31
+ return undefined;
32
+ }
33
+ return this.#takeLine(new Uint8Array(0));
34
+ }
35
+
36
+ #takeLine(tail: Uint8Array): Uint8Array {
37
+ if (this.#pending.length === 0) {
38
+ return tail;
39
+ }
40
+ let total = tail.byteLength;
41
+ for (const part of this.#pending) {
42
+ total += part.byteLength;
43
+ }
44
+ const line = new Uint8Array(total);
45
+ let offset = 0;
46
+ for (const part of this.#pending) {
47
+ line.set(part, offset);
48
+ offset += part.byteLength;
49
+ }
50
+ line.set(tail, offset);
51
+ this.#pending = [];
52
+ return line;
53
+ }
54
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * 宿主插口上的一条 MCP server。与 `@ycodium-ai/plugin-api` 的 `ExecutorMcpServer` 同形,
3
+ * 这个包不依赖插件 API,所以在此处按结构重述。
4
+ */
5
+ export type HostMcpServerEntry = {
6
+ readonly name: string;
7
+ readonly transport:
8
+ | {
9
+ readonly type: "stdio";
10
+ readonly command: string;
11
+ readonly args?: ReadonlyArray<string> | undefined;
12
+ readonly env?: Readonly<Record<string, string>> | undefined;
13
+ }
14
+ | {
15
+ readonly type: "http" | "sse";
16
+ readonly url: string;
17
+ readonly headers?: Readonly<Record<string, string>> | undefined;
18
+ };
19
+ };
20
+
21
+ /**
22
+ * 宿主插口上的 MCP server 列表 → ACP `session/new` / `session/load` / `session/resume` 的 `mcpServers`。
23
+ *
24
+ * 「哪条给这只手、传输支不支持」宿主 `resolveMcpLaunchList` 已经按名片 `card.mcpTransports` 判完,这里只换形状。
25
+ * 注意:宿主内置的 `ycodium` 编排与记忆 MCP 固定使用 `type: "http"`;ACP 的 stdio 变体没有 `type` 字段,
26
+ * env 与 headers 都是 `{ name, value }` 数组。http / sse 要不要发给 agent,由执行器按 agent 握手里报的
27
+ * `agentCapabilities.mcpCapabilities`(或 `hooks.mcpCapabilities` 兜底)再筛一遍。
28
+ */
29
+ export function toAcpMcpServers(
30
+ entries: ReadonlyArray<HostMcpServerEntry> | undefined,
31
+ ): ReadonlyArray<{ readonly type?: string; readonly [key: string]: unknown }> {
32
+ return (entries ?? []).map((entry) =>
33
+ entry.transport.type === "stdio"
34
+ ? {
35
+ name: entry.name,
36
+ command: entry.transport.command,
37
+ args: [...(entry.transport.args ?? [])],
38
+ env: Object.entries(entry.transport.env ?? {}).map(([name, value]) => ({ name, value })),
39
+ }
40
+ : {
41
+ type: entry.transport.type,
42
+ name: entry.name,
43
+ url: entry.transport.url,
44
+ headers: Object.entries(entry.transport.headers ?? {}).map(([name, value]) => ({
45
+ name,
46
+ value,
47
+ })),
48
+ },
49
+ );
50
+ }
51
+
52
+ /**
53
+ * 校验名片 `card.mcpTransports` 声明的传输类型是否都会被 ACP 握手放行。
54
+ *
55
+ * 返回名片声明了、但 `initialize.agentCapabilities.mcpCapabilities`(叠加 `hooks.mcpCapabilities` 兜底后)
56
+ * 没有声明为 `true` 的传输列表(`"http"` / `"sse"`)。理想情况下专用 ACP 插件对该函数应返回空数组 `[]`;
57
+ * 非空说明宿主按名片放行给插件的该类 MCP(尤其是固定为 `"http"` 的宿主内置 `ycodium` MCP)会在建会话时被执行器筛掉。
58
+ */
59
+ export function unadvertisedAcpMcpTransports(input: {
60
+ readonly cardTransports: ReadonlyArray<"stdio" | "http" | "sse"> | null | undefined;
61
+ readonly agentCapabilities?:
62
+ | {
63
+ readonly mcpCapabilities?:
64
+ | { readonly http?: boolean; readonly sse?: boolean }
65
+ | null
66
+ | undefined;
67
+ readonly [key: string]: unknown;
68
+ }
69
+ | null
70
+ | undefined;
71
+ readonly hooksMcpCapabilities?: { readonly http?: boolean; readonly sse?: boolean } | undefined;
72
+ }): ReadonlyArray<"http" | "sse"> {
73
+ const effective = input.agentCapabilities?.mcpCapabilities ?? input.hooksMcpCapabilities;
74
+ const unadvertised: Array<"http" | "sse"> = [];
75
+ for (const transport of input.cardTransports ?? []) {
76
+ if (transport === "http" && effective?.http !== true && !unadvertised.includes("http")) {
77
+ unadvertised.push("http");
78
+ } else if (transport === "sse" && effective?.sse !== true && !unadvertised.includes("sse")) {
79
+ unadvertised.push("sse");
80
+ }
81
+ }
82
+ return unadvertised;
83
+ }
@@ -0,0 +1,138 @@
1
+ // 型号选择状态:从会话建立的响应里读出这只 agent 用哪条路切型号、当前是哪个、报了哪些。
2
+ import { findConfigOptionEntry } from "./config-options.ts";
3
+ import {
4
+ collectSessionConfigOptionValues,
5
+ collectSessionModelIds,
6
+ extractModelConfigId,
7
+ findSessionConfigOption,
8
+ type AcpSessionSetupResponse,
9
+ } from "./runtime-model.ts";
10
+ import { isRecord } from "./util.ts";
11
+
12
+ export type AcpModelSelectionState = {
13
+ readonly strategy: "session/set_model" | "config-option";
14
+ readonly sessionModelsAdvertised: boolean;
15
+ readonly modelConfigId: string | undefined;
16
+ readonly currentModelId: string | undefined;
17
+ /**
18
+ * `currentModelId` 是 agent 自己报的(建会话回包的 `models.currentModelId` / 型号配置项的 `currentValue`,
19
+ * 或切型号后回包 / 通知里的新值)。缺席表示它只是请求值的回声:`session/set_model` 的回包不带型号,
20
+ * 配置项写入没等到 agent 的回报时当前值是本地改的。
21
+ */
22
+ readonly currentModelReported?: true;
23
+ /** 手在握手里报的型号取值;写回 CLI 的只能是其中之一。 */
24
+ readonly advertisedModelValues: ReadonlyArray<string>;
25
+ /**
26
+ * 手最近报的整份 configOptions:建会话时那份,经 `session/set_config_option` 切型号后换成回包里的
27
+ * 新一份——力度档可以跟着型号变,按旧的那份认会把新型号才有的档当成不认识。
28
+ */
29
+ readonly configOptions?: unknown;
30
+ /** 判目录用的那份建会话回包(建会话时那份,运行中刷新过目录就换成刷新时那份);型号元数据从它读。 */
31
+ readonly catalogSetup?: unknown;
32
+ /**
33
+ * 写过型号却没等到确认:当前型号未知,但不是「agent 从来不报型号」。目录为空时也不能按后者放过,
34
+ * 下一轮明确选的型号照写。agent 再报出当前型号或写成功就撤掉。
35
+ */
36
+ readonly modelUnconfirmed?: true;
37
+ };
38
+
39
+ export function normalizeModelId(value: string | undefined): string | undefined {
40
+ return value?.trim() || undefined;
41
+ }
42
+
43
+ /**
44
+ * agent 新报了一份 configOptions(切型号或写档的回包、`config_option_update`):档表与当前型号照新报的认,
45
+ * 可选名单不跟着换,仍是最近一次完整目录(建会话时那份,或运行中刷新到的那份)。dsh 实测切走后回包里的
46
+ * 名单就没有旧型号了,跟着换的话,切回去会多一次不必要的目录刷新。
47
+ *
48
+ * `fromAgent` 为假表示这份表是本地在上一份上改出来的(写档的应答不带表),其中的型号项没有新证据:
49
+ * 当前型号只在它没变且原先就是 agent 报的时候继续算 agent 报的,不因此升级。
50
+ */
51
+ export function adoptReportedConfigOptions(
52
+ state: AcpModelSelectionState,
53
+ configOptions: unknown,
54
+ fromAgent = true,
55
+ ): AcpModelSelectionState {
56
+ const option =
57
+ state.modelConfigId === undefined
58
+ ? undefined
59
+ : findConfigOptionEntry(configOptions, state.modelConfigId);
60
+ const value = option?.["currentValue"];
61
+ const reported = typeof value === "string" ? normalizeModelId(value) : undefined;
62
+ if (reported === undefined) return { ...state, configOptions };
63
+ const { modelUnconfirmed: _confirmed, ...known } = state;
64
+ const stillReported =
65
+ fromAgent || (state.currentModelReported === true && reported === state.currentModelId);
66
+ const { currentModelReported: _stale, ...unreported } = known;
67
+ return {
68
+ ...(stillReported ? known : unreported),
69
+ configOptions,
70
+ currentModelId: reported,
71
+ ...(stillReported ? { currentModelReported: true as const } : {}),
72
+ };
73
+ }
74
+
75
+ /**
76
+ * 写出去没等到应答的那一项记成未知:清掉它在档表里的当前值;是型号项(或只报 `models` 的手切型号)就连当前型号一起清。
77
+ * 之后在这份表上回填出来的表不带这一项的值,认不回旧值;下一轮照请求重写。
78
+ */
79
+ export function forgetConfigOptionValue(
80
+ state: AcpModelSelectionState,
81
+ configId: string | undefined,
82
+ ): AcpModelSelectionState {
83
+ const forgetsModel = configId === undefined || configId === state.modelConfigId;
84
+ const { currentModelReported: _forgottenReport, ...withoutReport } = state;
85
+ const configOptions =
86
+ configId !== undefined && Array.isArray(state.configOptions)
87
+ ? state.configOptions.map((option: unknown) => {
88
+ if (!isRecord(option) || option["id"] !== configId) return option;
89
+ const { currentValue: _forgotten, ...rest } = option;
90
+ return rest;
91
+ })
92
+ : state.configOptions;
93
+ return {
94
+ ...(forgetsModel ? withoutReport : state),
95
+ configOptions,
96
+ ...(forgetsModel ? { currentModelId: undefined, modelUnconfirmed: true as const } : {}),
97
+ };
98
+ }
99
+
100
+ export function modelSelectionStateFromSetup(
101
+ setup: AcpSessionSetupResponse,
102
+ ): AcpModelSelectionState {
103
+ const sessionModels = isRecord(setup.models) ? setup.models : undefined;
104
+ const modelConfigId = extractModelConfigId(setup);
105
+ // 报了型号配置项就走它:回包带切完之后的整份档表,`session/set_model` 的回包不带(grok 两样都报,
106
+ // 档表另推通知,可能晚于回包)。只报 `models` 或两样都没报的选 set_model。当前型号和目录都没有时
107
+ // 发送守卫保持;已经知道当前型号却对不上请求时,先刷新一次再失败,不沿用这个型号。
108
+ const strategy =
109
+ modelConfigId !== undefined ? ("config-option" as const) : ("session/set_model" as const);
110
+ const modelConfigOption =
111
+ modelConfigId === undefined
112
+ ? undefined
113
+ : findSessionConfigOption(setup.configOptions, modelConfigId);
114
+ const configModel = modelConfigOption?.currentValue;
115
+ const currentModelId =
116
+ strategy === "config-option"
117
+ ? typeof configModel === "string"
118
+ ? normalizeModelId(configModel)
119
+ : undefined
120
+ : typeof sessionModels?.["currentModelId"] === "string"
121
+ ? normalizeModelId(sessionModels["currentModelId"])
122
+ : undefined;
123
+ return {
124
+ strategy,
125
+ sessionModelsAdvertised: sessionModels !== undefined,
126
+ modelConfigId,
127
+ currentModelId,
128
+ ...(currentModelId === undefined ? {} : { currentModelReported: true as const }),
129
+ advertisedModelValues:
130
+ strategy === "config-option"
131
+ ? modelConfigOption === undefined
132
+ ? []
133
+ : collectSessionConfigOptionValues(modelConfigOption)
134
+ : collectSessionModelIds(sessionModels),
135
+ configOptions: setup.configOptions,
136
+ catalogSetup: setup,
137
+ };
138
+ }
@@ -0,0 +1,80 @@
1
+ // 发送前的型号判决。纯函数:不刷新、不写会话。刷新目录后在原会话上写的步骤在 session.ts。
2
+ import { withFailureCategory } from "./failureCategory.ts";
3
+ import { normalizeModelId, type AcpModelSelectionState } from "./model-selection.ts";
4
+ import { matchAdvertisedModelValue } from "./runtime-model.ts";
5
+
6
+ export type ModelSendJudgment =
7
+ | { readonly kind: "keep" }
8
+ | { readonly kind: "switch"; readonly value: string }
9
+ | { readonly kind: "refresh" };
10
+
11
+ export function judgeRequestedModel(input: {
12
+ readonly state: AcpModelSelectionState;
13
+ readonly requestedModelId: string | undefined;
14
+ }): ModelSendJudgment {
15
+ const requested = normalizeModelId(input.requestedModelId);
16
+ const current = input.state.currentModelId;
17
+ if (requested === undefined || requested === current) return { kind: "keep" };
18
+ const hasCatalog = input.state.advertisedModelValues.length > 0;
19
+ const hasCurrent = current !== undefined;
20
+ // 当前型号和目录都没报,没有可判的事实,沿用这只手自己的型号。写过没确认的不算:照请求重写。
21
+ if (!hasCatalog && !hasCurrent && input.state.modelUnconfirmed !== true) return { kind: "keep" };
22
+ const canSwitch = canSwitchModel(input.state);
23
+ const value = hasCatalog
24
+ ? matchAdvertisedModelValue(requested, input.state.advertisedModelValues)
25
+ : undefined;
26
+ // 两边都缺席时 `undefined === undefined` 会当成「已经是当前型号」。目录里对不上就刷新,再交给 agent 判。
27
+ if (value !== undefined && value === current) return { kind: "keep" };
28
+ if (value !== undefined && canSwitch) return { kind: "switch", value };
29
+ return { kind: "refresh" };
30
+ }
31
+
32
+ /** 这只手有没有在会话里切型号的通道。 */
33
+ export const canSwitchModel = (state: AcpModelSelectionState): boolean =>
34
+ (state.strategy === "session/set_model" && state.sessionModelsAdvertised) ||
35
+ (state.strategy === "config-option" && state.modelConfigId !== undefined);
36
+
37
+ export function modelUnavailableError(
38
+ requestedModelId: string,
39
+ currentModelId: string | undefined,
40
+ ): Error {
41
+ const current = currentModelId ?? "its own model";
42
+ return withFailureCategory(
43
+ new Error(
44
+ `Requested model "${requestedModelId}" is not in this agent's catalog; it is on "${current}". This turn was not sent. Refresh the model list in this agent's settings and try again.`,
45
+ ),
46
+ "model-unavailable",
47
+ );
48
+ }
49
+
50
+ /** 刷新整段的内部期限到了。不带失败类别,免得被当成已经给用户看的那句。 */
51
+ export class ModelCatalogRefreshTimeoutError extends Error {
52
+ constructor() {
53
+ super("model catalog refresh timed out");
54
+ this.name = "ModelCatalogRefreshTimeoutError";
55
+ }
56
+ }
57
+
58
+ export function modelRefreshTimedOutError(requestedModelId: string): Error {
59
+ return withFailureCategory(
60
+ new Error(
61
+ `Refreshing this agent's model list timed out, so this turn was not sent. Requested model "${requestedModelId}".`,
62
+ ),
63
+ "model-unavailable",
64
+ );
65
+ }
66
+
67
+ export { MODEL_CATALOG_REFRESH_TIMEOUT_MS } from "./refreshDeadline.ts";
68
+
69
+ export function modelRefreshFailedError(requestedModelId: string, error: unknown): Error {
70
+ const detail =
71
+ error instanceof Error && error.message.trim().length > 0
72
+ ? error.message
73
+ : "the model list could not be read";
74
+ return withFailureCategory(
75
+ new Error(
76
+ `Refreshing this agent's model list failed (${detail}), so this turn was not sent. Requested model "${requestedModelId}".`,
77
+ ),
78
+ "model-unavailable",
79
+ );
80
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * 单槽互斥。不是 Scope:调用方自己 acquire/release,dispose 时 drain 等待者。
3
+ */
4
+ export class Mutex {
5
+ private locked = false;
6
+ private readonly waiters: Array<() => void> = [];
7
+
8
+ get isLocked(): boolean {
9
+ return this.locked;
10
+ }
11
+
12
+ acquire(): Promise<void> {
13
+ if (!this.locked) {
14
+ this.locked = true;
15
+ return Promise.resolve();
16
+ }
17
+ return new Promise((resolve) => {
18
+ this.waiters.push(resolve);
19
+ });
20
+ }
21
+
22
+ tryAcquire(): boolean {
23
+ if (this.locked) {
24
+ return false;
25
+ }
26
+ this.locked = true;
27
+ return true;
28
+ }
29
+
30
+ release(): void {
31
+ const next = this.waiters.shift();
32
+ if (next) {
33
+ next();
34
+ return;
35
+ }
36
+ this.locked = false;
37
+ }
38
+
39
+ async runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {
40
+ await this.acquire();
41
+ try {
42
+ return await fn();
43
+ } finally {
44
+ this.release();
45
+ }
46
+ }
47
+ }
@@ -0,0 +1,167 @@
1
+ import type {
2
+ ExecutorSessionImportActivity,
3
+ ExecutorSessionImportMessage,
4
+ } from "@ycodium-ai/plugin-api/executor";
5
+
6
+ import {
7
+ inputPayload,
8
+ outputPayload,
9
+ reasoning,
10
+ toolInput,
11
+ } from "./_private/ycodium-jsonl-stream/sessionTranscript.ts";
12
+
13
+ import { canonicalItemTypeFromAcpToolKind } from "./tool-presentation.ts";
14
+ import { asTrimmedString, isRecord } from "./util.ts";
15
+
16
+ type TextItem = {
17
+ readonly type: "user_message_chunk" | "agent_message_chunk" | "agent_thought_chunk";
18
+ readonly id: string | undefined;
19
+ readonly chunks: string[];
20
+ readonly sourceOrder: number;
21
+ };
22
+ type ToolItem = {
23
+ readonly type: "tool_call";
24
+ readonly id: string;
25
+ readonly data: Record<string, unknown>;
26
+ readonly sourceOrder: number;
27
+ completionOrder?: number;
28
+ };
29
+
30
+ /** ACP v1 agents may omit message ids. In that case contiguous chunks of the same kind form one item. */
31
+ export function createAcpImportTranscript() {
32
+ const items: Array<TextItem | ToolItem> = [];
33
+ const messagesById = new Map<string, TextItem>();
34
+ const toolsById = new Map<string, ToolItem>();
35
+ let lastText: TextItem | undefined;
36
+ let nextOrder = 0;
37
+
38
+ function addUpdate(update: Record<string, unknown>) {
39
+ const type = update["sessionUpdate"];
40
+ if (
41
+ type === "user_message_chunk" ||
42
+ type === "agent_message_chunk" ||
43
+ type === "agent_thought_chunk"
44
+ ) {
45
+ const id = asTrimmedString(update["messageId"]);
46
+ const key = id === undefined ? undefined : JSON.stringify([type, id]);
47
+ const previous =
48
+ key === undefined
49
+ ? lastText?.type === type && lastText.id === undefined
50
+ ? lastText
51
+ : undefined
52
+ : messagesById.get(key);
53
+ const item = previous ?? { type, id, chunks: [], sourceOrder: nextOrder++ };
54
+ if (previous === undefined) {
55
+ items.push(item);
56
+ if (key !== undefined) messagesById.set(key, item);
57
+ }
58
+ lastText = item;
59
+ const content = update["content"];
60
+ if (isRecord(content) && content["type"] === "text" && typeof content["text"] === "string")
61
+ item.chunks.push(content["text"]);
62
+ return;
63
+ }
64
+
65
+ if (type !== "tool_call" && type !== "tool_call_update") return;
66
+ lastText = undefined;
67
+ const id = asTrimmedString(update["toolCallId"]);
68
+ if (id === undefined) return;
69
+ const previous = toolsById.get(id);
70
+ const item: ToolItem = previous ?? {
71
+ type: "tool_call",
72
+ id,
73
+ data: {},
74
+ sourceOrder: nextOrder++,
75
+ };
76
+ Object.assign(item.data, update);
77
+ if (previous === undefined) {
78
+ toolsById.set(id, item);
79
+ items.push(item);
80
+ }
81
+ const status = update["status"];
82
+ if (status === "completed" || status === "failed") item.completionOrder ??= nextOrder++;
83
+ }
84
+
85
+ function finish() {
86
+ const messages: ExecutorSessionImportMessage[] = [];
87
+ const activities: ExecutorSessionImportActivity[] = [];
88
+ for (const item of items) {
89
+ const { sourceOrder } = item;
90
+ // ACP v1 does not carry per-item times. The host supplies a stable timestamp on import.
91
+ const identity = { sourceOrder, createdAt: "" };
92
+ if (item.type === "tool_call") {
93
+ const data = item.data;
94
+ const status = data["status"];
95
+ const content = Array.isArray(data["content"]) ? data["content"] : [];
96
+ const output = content
97
+ .flatMap((entry: unknown) => {
98
+ if (!isRecord(entry) || entry["type"] !== "content") return [];
99
+ const block = entry["content"];
100
+ return isRecord(block) && block["type"] === "text" && typeof block["text"] === "string"
101
+ ? [block["text"]]
102
+ : [];
103
+ })
104
+ .join("\n");
105
+ const sourceId = `acp:tool:${JSON.stringify(item.id)}`;
106
+ const summary = asTrimmedString(data["title"]) ?? item.id;
107
+ const payload = {
108
+ toolCallId: item.id,
109
+ itemType: canonicalItemTypeFromAcpToolKind(asTrimmedString(data["kind"])),
110
+ ...inputPayload(toolInput(data["rawInput"])),
111
+ };
112
+ activities.push({
113
+ ...identity,
114
+ sourceId,
115
+ kind: "tool.started",
116
+ tone: "tool",
117
+ summary,
118
+ payload:
119
+ item.completionOrder === undefined
120
+ ? { ...payload, ...outputPayload(output || undefined) }
121
+ : payload,
122
+ });
123
+ if (item.completionOrder !== undefined) {
124
+ activities.push({
125
+ ...identity,
126
+ sourceId: `${sourceId}:completion`,
127
+ sourceOrder: item.completionOrder,
128
+ kind: "tool.completed",
129
+ tone: status === "failed" ? "error" : "tool",
130
+ summary,
131
+ payload: {
132
+ ...payload,
133
+ status: status === "failed" ? "failed" : "completed",
134
+ ...outputPayload(output || undefined),
135
+ },
136
+ });
137
+ }
138
+ continue;
139
+ }
140
+ const text = item.chunks.join("");
141
+ if (text.trim() === "") continue;
142
+ const sourceId =
143
+ item.id === undefined
144
+ ? `acp:${item.type}:order:${sourceOrder}`
145
+ : `acp:${item.type}:id:${item.id}`;
146
+ if (item.type === "agent_thought_chunk") {
147
+ const activity = reasoning({ ...identity, sourceId }, text, "reasoning_text");
148
+ activities.push({ ...activity, payload: { ...activity.payload, chars: text.length } });
149
+ } else {
150
+ messages.push({
151
+ ...identity,
152
+ sourceId,
153
+ role: item.type === "user_message_chunk" ? "user" : "assistant",
154
+ text,
155
+ });
156
+ }
157
+ }
158
+ return {
159
+ messages,
160
+ activities: activities.sort((a, b) => a.sourceOrder - b.sourceOrder),
161
+ availableMessages: messages.length,
162
+ availableActivities: activities.length,
163
+ };
164
+ }
165
+
166
+ return { addUpdate, finish };
167
+ }