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,271 @@
1
+ // @effect-diagnostics nodeBuiltinImport:off globalDate:off - ACP instances run in the Promise-only plugin API.
2
+ import * as NodePath from "node:path";
3
+
4
+ import type {
5
+ ExecutorHost,
6
+ ExecutorInstance,
7
+ ExecutorSessionCandidate,
8
+ ExecutorSessionImportInput,
9
+ } from "@ycodium-ai/plugin-api/executor";
10
+ import type {
11
+ isOperationCleanupError,
12
+ withProcessOperation,
13
+ OperationSpawnInput,
14
+ } from "@ycodium-ai/plugin-api/process-operation";
15
+ import { nodeStreamsFromHandle } from "./_private/ycodium-executor-common/nodeStreams.ts";
16
+
17
+ import { createAcpConnection, type AcpConnection } from "./connection.ts";
18
+ import { acpModelChoicesFromConfigOptions } from "./config-options.ts";
19
+ import { acpAgentVersion } from "./probe.ts";
20
+ import { acpInitializePayload, type AcpClientInfo } from "./handshake.ts";
21
+ import { createAcpImportTranscript } from "./native-session-transcript.ts";
22
+ import { PROTOCOL_VERSION } from "./protocol.ts";
23
+ import { isSessionUpdateEnvelope } from "./session-update.ts";
24
+ import { asTrimmedString, isRecord } from "./util.ts";
25
+
26
+ type NativeSessionLaunch = {
27
+ readonly spawn: OperationSpawnInput;
28
+ readonly filterStdout?: (stdout: AsyncIterable<Uint8Array>) => AsyncIterable<Uint8Array>;
29
+ readonly release?: (exited: boolean) => Promise<void>;
30
+ };
31
+
32
+ function isWithinDirectory(cwd: string, root: string): boolean {
33
+ const relative = NodePath.relative(root, cwd);
34
+ return (
35
+ relative !== ".." && !relative.startsWith(`..${NodePath.sep}`) && !NodePath.isAbsolute(relative)
36
+ );
37
+ }
38
+
39
+ function assertHistoryCapabilities(initialize: unknown, requireResume: boolean) {
40
+ const init = isRecord(initialize) ? initialize : {};
41
+ const agent = isRecord(init["agentCapabilities"]) ? init["agentCapabilities"] : {};
42
+ const session = isRecord(agent["sessionCapabilities"]) ? agent["sessionCapabilities"] : {};
43
+ if (
44
+ init["protocolVersion"] !== PROTOCOL_VERSION ||
45
+ agent["loadSession"] !== true ||
46
+ !isRecord(session["list"]) ||
47
+ (requireResume && !isRecord(session["resume"]))
48
+ ) {
49
+ const version = acpAgentVersion(init);
50
+ throw new Error(
51
+ `This ACP agent${version ? ` (${version})` : ""} does not support native session import.`,
52
+ );
53
+ }
54
+ }
55
+
56
+ /** 读取 ACP 代理声明的当前模型;不把目录中的第一项当作已选模型。 */
57
+ function reportedModel(setup: unknown) {
58
+ if (!isRecord(setup)) return undefined;
59
+ const options = Array.isArray(setup.configOptions) ? setup.configOptions : [];
60
+ const selected = options.find(
61
+ (opt: unknown) => isRecord(opt) && (opt.category === "model" || opt.id === "model"),
62
+ );
63
+ if (isRecord(selected)) {
64
+ const choices = acpModelChoicesFromConfigOptions([{ ...selected, category: "model" }]);
65
+ const model =
66
+ choices?.find((choice) => choice.isDefault)?.value ?? asTrimmedString(selected.currentValue);
67
+ if (model) return model;
68
+ }
69
+ return isRecord(setup.models) ? asTrimmedString(setup.models.currentModelId) : undefined;
70
+ }
71
+
72
+ async function* listCandidates(connection: AcpConnection, cwd: string) {
73
+ let cursor: string | undefined;
74
+ const cursors = new Set<string>();
75
+ do {
76
+ const page = await connection.request<unknown>("session/list", {
77
+ cwd,
78
+ ...(cursor === undefined ? {} : { cursor }),
79
+ });
80
+ if (!isRecord(page) || !Array.isArray(page["sessions"]))
81
+ throw new Error("ACP session/list returned an invalid response.");
82
+ for (const entry of page["sessions"]) {
83
+ if (!isRecord(entry)) continue;
84
+ const id = entry["sessionId"];
85
+ const directory = entry["cwd"];
86
+ if (
87
+ typeof id !== "string" ||
88
+ id.length === 0 ||
89
+ typeof directory !== "string" ||
90
+ !NodePath.isAbsolute(directory)
91
+ )
92
+ continue;
93
+ const updatedAt =
94
+ typeof entry["updatedAt"] === "string" ? Date.parse(entry["updatedAt"]) : NaN;
95
+ yield {
96
+ nativeSessionId: id,
97
+ cwd: directory,
98
+ title: asTrimmedString(entry["title"]) ?? null,
99
+ preview: null,
100
+ model: null,
101
+ updatedAt: Number.isFinite(updatedAt) ? updatedAt : 0,
102
+ turnCount: 0,
103
+ availability: "importable" as const,
104
+ openElsewhere: false,
105
+ };
106
+ }
107
+ const nextCursor = page["nextCursor"];
108
+ cursor = typeof nextCursor === "string" && nextCursor.length > 0 ? nextCursor : undefined;
109
+ if (cursor !== undefined) {
110
+ if (cursors.has(cursor)) throw new Error("ACP session/list repeated its pagination cursor.");
111
+ cursors.add(cursor);
112
+ }
113
+ } while (cursor !== undefined);
114
+ }
115
+
116
+ /** Query an isolated ACP connection. Only session/list and history replay are sent after initialize. */
117
+ export function createAcpNativeSessions(input: {
118
+ readonly host: ExecutorHost;
119
+ readonly processOperation: {
120
+ readonly withProcessOperation: typeof withProcessOperation;
121
+ readonly isOperationCleanupError: typeof isOperationCleanupError;
122
+ };
123
+ readonly clientInfo: AcpClientInfo;
124
+ readonly storageKey: string;
125
+ readonly resumeSchemaVersion: number;
126
+ readonly requireResume?: boolean;
127
+ readonly acquireLaunch: (cwd: string) => NativeSessionLaunch | Promise<NativeSessionLaunch>;
128
+ }): NonNullable<ExecutorInstance["sessions"]> & { readonly storageKey: string } {
129
+ async function withConnection<T>(
130
+ cwd: string,
131
+ signal: AbortSignal | undefined,
132
+ run: (connection: AcpConnection) => Promise<T>,
133
+ onNotification?: NonNullable<Parameters<typeof createAcpConnection>[0]["onNotification"]>,
134
+ ): Promise<T> {
135
+ if (!NodePath.isAbsolute(cwd))
136
+ throw new Error("ACP session import requires an absolute working directory.");
137
+ signal?.throwIfAborted();
138
+ const launch = await input.acquireLaunch(cwd);
139
+ let exited = true;
140
+ try {
141
+ return await input.processOperation.withProcessOperation(
142
+ input.host,
143
+ { signal, timeoutMs: 90_000 },
144
+ async (operation) => {
145
+ const handle = await operation.spawn(launch.spawn);
146
+ const stdout = launch.filterStdout?.(handle.stdout) ?? handle.stdout;
147
+ const stdoutDone = Promise.withResolvers<void>();
148
+ const { readable, writable, stderrTail } = nodeStreamsFromHandle({
149
+ ...handle,
150
+ stdout: (async function* () {
151
+ try {
152
+ yield* stdout;
153
+ } finally {
154
+ stdoutDone.resolve();
155
+ }
156
+ })(),
157
+ });
158
+ operation.track(stdoutDone.promise);
159
+ operation.track(stderrTail());
160
+ const connection = createAcpConnection({
161
+ readable,
162
+ writable,
163
+ ...(onNotification === undefined ? {} : { onNotification }),
164
+ });
165
+ operation.defer(() => {
166
+ const closing = connection.close();
167
+ readable.destroy();
168
+ return closing;
169
+ });
170
+ const initialize = await connection.request(
171
+ "initialize",
172
+ acpInitializePayload(input.clientInfo),
173
+ );
174
+ assertHistoryCapabilities(initialize, input.requireResume ?? false);
175
+ return run(connection);
176
+ },
177
+ );
178
+ } catch (error) {
179
+ exited = !input.processOperation.isOperationCleanupError(error);
180
+ throw error;
181
+ } finally {
182
+ await launch.release?.(exited);
183
+ }
184
+ }
185
+
186
+ const readImport = async ({ nativeSessionId, cwd, signal }: ExecutorSessionImportInput) => {
187
+ if (cwd === undefined || !NodePath.isAbsolute(cwd))
188
+ throw new Error("ACP session import requires an absolute working directory.");
189
+ const transcript = createAcpImportTranscript();
190
+ let collecting = false;
191
+ let replayModel: string | undefined;
192
+ return withConnection(
193
+ cwd,
194
+ signal,
195
+ async (connection) => {
196
+ let match: ExecutorSessionCandidate | undefined;
197
+ for await (const candidate of listCandidates(connection, cwd)) {
198
+ if (candidate.nativeSessionId !== nativeSessionId) continue;
199
+ if (!(isWithinDirectory(candidate.cwd, cwd) && isWithinDirectory(cwd, candidate.cwd)))
200
+ continue;
201
+ match = candidate;
202
+ break;
203
+ }
204
+ if (match === undefined)
205
+ throw new Error(
206
+ "The native ACP session does not match the requested session and directory.",
207
+ );
208
+ collecting = true;
209
+ const load = connection.begin(
210
+ "session/load",
211
+ {
212
+ sessionId: nativeSessionId,
213
+ cwd: match.cwd,
214
+ mcpServers: [],
215
+ },
216
+ undefined,
217
+ () => {
218
+ collecting = false;
219
+ },
220
+ );
221
+ const [setup] = await Promise.all([load.response, load.written]);
222
+ return {
223
+ ...transcript.finish(),
224
+ title: match.title,
225
+ model: reportedModel(setup) ?? replayModel ?? null,
226
+ resumeCursor: { schemaVersion: input.resumeSchemaVersion, sessionId: nativeSessionId },
227
+ };
228
+ },
229
+ ({ method, params }) => {
230
+ if (
231
+ collecting &&
232
+ method === "session/update" &&
233
+ isSessionUpdateEnvelope(params) &&
234
+ params.sessionId === nativeSessionId
235
+ ) {
236
+ replayModel = reportedModel(params.update) ?? replayModel;
237
+ transcript.addUpdate(params.update);
238
+ }
239
+ },
240
+ );
241
+ };
242
+
243
+ return {
244
+ storageKey: input.storageKey,
245
+ scan: ({ projectId, directory, signal }) => {
246
+ const cwd = directory ?? input.host.workspacePath(projectId);
247
+ return withConnection(cwd, signal, async (connection) => {
248
+ const candidates = new Map<string, ExecutorSessionCandidate>();
249
+ for await (const candidate of listCandidates(connection, cwd)) {
250
+ if (isWithinDirectory(candidate.cwd, cwd))
251
+ candidates.set(candidate.nativeSessionId, candidate);
252
+ }
253
+ return { candidates: [...candidates.values()].sort((a, b) => b.updatedAt - a.updatedAt) };
254
+ });
255
+ },
256
+ readImport,
257
+ read: async ({ nativeSessionId, cwd, signal }) => {
258
+ const session = await readImport({
259
+ nativeSessionId,
260
+ cwd,
261
+ ...(signal === undefined ? {} : { signal }),
262
+ });
263
+ return {
264
+ nativeSessionId,
265
+ resumeCursor: session.resumeCursor,
266
+ model: session.model,
267
+ messages: session.messages.map(({ role, text }) => ({ role, text })),
268
+ };
269
+ },
270
+ };
271
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * 这一轮还在跑的工具调用,从执行器那份工具调用状态里读(生命周期只在 `retainToolCallUpdate` 一处维护)。
3
+ * 只出事实:`kind`、原始 `title`、`rawInput` 原样,不解析、不拼接,也不判哪条算命令——各家报法不同
4
+ * (有的顶层 `kind` 是 `execute`,DSH 的 shell 是 `kind: "other"`、`title: "bash"`),由插件读出来自己判。
5
+ */
6
+ import type { AcpToolCallTrackedState } from "./events.ts";
7
+
8
+ /** 已经进入运行态、还没结束的一条。 */
9
+ export type AcpOpenToolCall = {
10
+ readonly toolCallId: string;
11
+ readonly turnId: string | undefined;
12
+ /** 第一次进入运行态时宿主收到通知的时刻(墙钟毫秒)。 */
13
+ readonly startedAtMs: number;
14
+ readonly kind: string | undefined;
15
+ /** 通知里的 `title` 原文,不是展示标题。 */
16
+ readonly title: string | undefined;
17
+ /** 通知里的 `rawInput` 原值;一直没带就是 `undefined`。 */
18
+ readonly rawInput: unknown;
19
+ };
20
+
21
+ /** 属于 `turnId` 这一轮、已经跑起来的那些。只读,调用方拿到的是新数组。 */
22
+ export function readOpenToolCalls(
23
+ toolCalls: ReadonlyMap<string, AcpToolCallTrackedState>,
24
+ turnId: string | undefined,
25
+ ): ReadonlyArray<AcpOpenToolCall> {
26
+ const running: AcpOpenToolCall[] = [];
27
+ for (const tracked of toolCalls.values()) {
28
+ if (tracked.turnId !== turnId || tracked.startedAtMs === undefined) continue;
29
+ running.push({
30
+ toolCallId: tracked.state.toolCallId,
31
+ turnId: tracked.turnId,
32
+ startedAtMs: tracked.startedAtMs,
33
+ kind: tracked.state.kind,
34
+ title: tracked.rawTitle,
35
+ rawInput: tracked.state.data["rawInput"],
36
+ });
37
+ }
38
+ return running;
39
+ }
@@ -0,0 +1,49 @@
1
+ import type { AcpPermissionRequest } from "./runtime-model.ts";
2
+ import { isRecord } from "./util.ts";
3
+
4
+ /** 与 ProviderRequestStatement 同形;纯 ACP 包不依赖宿主契约。只用于显示,不参与自动批准。 */
5
+ export type AcpRequestStatement = {
6
+ readonly description?: string;
7
+ readonly justification?: string;
8
+ readonly command?: string;
9
+ readonly outsideSandbox?: true;
10
+ readonly coveredArgs?: ReadonlyArray<string>;
11
+ };
12
+
13
+ /** 通用 ACP 只认 rawInput 明示的陈述,不从请求提示语猜命令或理由。 */
14
+ export function defaultPermissionStatement(request: AcpPermissionRequest): AcpRequestStatement {
15
+ const rawInput = request.toolCall?.data["rawInput"];
16
+ const input = isRecord(rawInput) ? rawInput : {};
17
+ const coveredArgs: string[] = [];
18
+ const text = (name: string): string | undefined => {
19
+ const value = input[name];
20
+ if (typeof value !== "string" || value.trim().length === 0) return undefined;
21
+ coveredArgs.push(name);
22
+ return value;
23
+ };
24
+ const description = text("description");
25
+ const justification = text("justification") ?? text("reason");
26
+ const command =
27
+ request.kind === "execute"
28
+ ? (text("command") ?? text("cmd") ?? request.toolCall?.command)
29
+ : undefined;
30
+ let outsideSandbox = false;
31
+ for (const name of ["sandbox_permissions", "sandboxPermissions", "dangerouslyDisableSandbox"]) {
32
+ const value = input[name];
33
+ const outside =
34
+ name === "dangerouslyDisableSandbox"
35
+ ? value === true || value === "true"
36
+ : typeof value === "string" && /full[-_]access|danger|escalat/i.test(value);
37
+ if (!outside) continue;
38
+ outsideSandbox = true;
39
+ coveredArgs.push(name);
40
+ }
41
+ if ("timeoutMs" in input) coveredArgs.push("timeoutMs");
42
+ return {
43
+ ...(description !== undefined ? { description } : {}),
44
+ ...(justification !== undefined ? { justification } : {}),
45
+ ...(command !== undefined ? { command } : {}),
46
+ ...(outsideSandbox ? { outsideSandbox: true } : {}),
47
+ ...(coveredArgs.length > 0 ? { coveredArgs } : {}),
48
+ };
49
+ }
@@ -0,0 +1,95 @@
1
+ // @effect-diagnostics nodeBuiltinImport:off
2
+ /**
3
+ * acp / dsh 探测目录共用的后半段:建探测目录、起进程、握手,然后交给调用方问目录。
4
+ * spawn 由调用方注入(宿主的 `host.process.spawn` 只有插件够得着)。
5
+ * 握手失败与问目录失败都收成 `threw`,进程仍在 `finally` 里关掉:挂住的握手不能留给状态刷新。
6
+ * `reuse` 是否再套一层 `raceAbort` 各家不同,留在 `run` 里。
7
+ */
8
+ import * as NodeFS from "node:fs";
9
+ import type * as NodeStream from "node:stream";
10
+
11
+ import { nodeStreamsFromHandle, type SpawnHandle } from "./_private/ycodium-executor-common/nodeStreams.ts";
12
+ import { raceAbort } from "./_private/ycodium-executor-common/raceAbort.ts";
13
+
14
+ import type { AcpClientInfo } from "./handshake.ts";
15
+ import { openAcpProbeHandshake, type AcpProbeHandshake } from "./probe.ts";
16
+ import { acpProbeFailureDetail, type AcpProbeNotStarted } from "./probe-session.ts";
17
+
18
+ type ProbeHandle = SpawnHandle & {
19
+ readonly kill: (signal: "SIGTERM") => Promise<unknown>;
20
+ };
21
+
22
+ type ProbeOptions<T> = {
23
+ readonly cwd: string;
24
+ /** 显式 `undefined` 与缺席一样:不把取消传进握手。 */
25
+ readonly signal?: AbortSignal | undefined;
26
+ readonly clientInfo: AcpClientInfo;
27
+ readonly requestTimeoutMs: number;
28
+ /** 与会话那侧同一个值;不传就不要写进握手。 */
29
+ readonly subagentSessions?: boolean;
30
+ readonly spawn: (
31
+ cwd: string,
32
+ ) => Promise<{ readonly kind: "spawned"; readonly handle: ProbeHandle } | AcpProbeNotStarted>;
33
+ readonly run: (handshake: AcpProbeHandshake) => Promise<T>;
34
+ };
35
+
36
+ type ProbeResult<T> =
37
+ | AcpProbeNotStarted
38
+ | {
39
+ readonly kind: "threw";
40
+ readonly error: unknown;
41
+ readonly handshakeOpened: boolean;
42
+ readonly initializeResult: unknown;
43
+ }
44
+ | { readonly kind: "ok"; readonly value: T };
45
+
46
+ export async function withAcpProbeProcess<T>(
47
+ input: ProbeOptions<T>,
48
+ ): Promise<
49
+ ProbeResult<T> | { readonly kind: "mkdir-failed"; readonly detail: string | undefined }
50
+ > {
51
+ try {
52
+ NodeFS.mkdirSync(input.cwd, { recursive: true });
53
+ } catch (error) {
54
+ return { kind: "mkdir-failed", detail: acpProbeFailureDetail(error) };
55
+ }
56
+ return runAcpProbeProcess(input);
57
+ }
58
+
59
+ /** 在已有工作目录内启动并关闭一次 ACP 探测。 */
60
+ export async function runAcpProbeProcess<T>(input: ProbeOptions<T>): Promise<ProbeResult<T>> {
61
+ const spawned = await input.spawn(input.cwd);
62
+ if (spawned.kind !== "spawned") return spawned;
63
+ const handle = spawned.handle;
64
+
65
+ let handshake: AcpProbeHandshake | undefined;
66
+ try {
67
+ const streams: {
68
+ readonly readable: NodeStream.Readable;
69
+ readonly writable: NodeStream.Writable;
70
+ } = nodeStreamsFromHandle(handle);
71
+ handshake = await raceAbort(
72
+ openAcpProbeHandshake({
73
+ readable: streams.readable,
74
+ writable: streams.writable,
75
+ clientInfo: input.clientInfo,
76
+ requestTimeoutMs: input.requestTimeoutMs,
77
+ ...(input.subagentSessions === undefined
78
+ ? {}
79
+ : { subagentSessions: input.subagentSessions }),
80
+ }),
81
+ input.signal,
82
+ );
83
+ return { kind: "ok", value: await input.run(handshake) };
84
+ } catch (error) {
85
+ return {
86
+ kind: "threw",
87
+ error,
88
+ handshakeOpened: handshake !== undefined,
89
+ initializeResult: handshake?.initializeResult,
90
+ };
91
+ } finally {
92
+ await handshake?.close().catch(() => undefined);
93
+ await handle.kill("SIGTERM").catch(() => undefined);
94
+ }
95
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 建会话才问得到目录的那几家共用的探测步骤:复用自己那条探测会话、把力度档翻成选项描述符、
3
+ * 失败原话与「没起来」那一档的形状。
4
+ */
5
+ import { acpEffortConfigState, findAcpEffortConfig } from "./config-options.ts";
6
+ import type { AcpProbeHandshake } from "./probe.ts";
7
+ import { isRecord } from "./util.ts";
8
+
9
+ /** 进程没起来:找不到程序、路径不存在或不可执行是 `not-installed`,其它启动失败是 `error`。 */
10
+ export type AcpProbeNotStarted = {
11
+ readonly kind: "not-started";
12
+ readonly readiness: "not-installed" | "error";
13
+ readonly detail: string | undefined;
14
+ };
15
+
16
+ /** 出错的原话,进快照的 `detail`。 */
17
+ export const acpProbeFailureDetail = (error: unknown): string | undefined =>
18
+ (error instanceof Error ? error.message : String(error)).trim() || undefined;
19
+
20
+ /** `session/list` 里认自己那条探测会话:cwd 等于探测专用目录、sessionId 非空的第一条。 */
21
+ export function findAcpProbeSessionId(listed: unknown, probeCwd: string): string | undefined {
22
+ if (!isRecord(listed) || !Array.isArray(listed["sessions"])) return undefined;
23
+ for (const entry of listed["sessions"]) {
24
+ if (!isRecord(entry)) continue;
25
+ if (entry["cwd"] !== probeCwd) continue;
26
+ const sessionId = entry["sessionId"];
27
+ if (typeof sessionId === "string" && sessionId.length > 0) return sessionId;
28
+ }
29
+ return undefined;
30
+ }
31
+
32
+ /**
33
+ * 探测会话:有自己那条就 resume(不新建记录),没有才 new;resume 失败也退回 new。
34
+ * `session/close` 之后记录仍在列表里,每次新建就会在用户自己的会话列表里堆垃圾。
35
+ */
36
+ export async function reuseAcpProbeSession(
37
+ handshake: AcpProbeHandshake,
38
+ probeCwd: string,
39
+ ): Promise<unknown> {
40
+ const listed = await handshake.request("session/list", {}).catch(() => undefined);
41
+ const reusable = findAcpProbeSessionId(listed, probeCwd);
42
+ if (reusable !== undefined) {
43
+ const resumed = await handshake
44
+ .request("session/resume", { sessionId: reusable, cwd: probeCwd, mcpServers: [] })
45
+ .catch(() => undefined);
46
+ if (resumed !== undefined) return resumed;
47
+ }
48
+ return handshake.request("session/new", { cwd: probeCwd, mcpServers: [] });
49
+ }
50
+
51
+ /**
52
+ * 会话回包里的力度档 → 选项描述符。三态:说不出(没报这一项、有读不懂的选项)是 `unknown`,
53
+ * 调用方不报;明确空表报空描述符,让宿主清掉旧档位;否则一格 select。
54
+ *
55
+ * ACP 把力度档报成会话级的一项,不是每模型一份:探测只建一条会话,拿到的是当前默认模型那一份。
56
+ */
57
+ export function acpEffortCapabilities(
58
+ configOptions: unknown,
59
+ descriptor: { readonly id: string; readonly fallbackLabel: string },
60
+ ) {
61
+ const state = acpEffortConfigState(configOptions);
62
+ if (state === "unknown") return "unknown" as const;
63
+ if (state === "none") return { optionDescriptors: [] };
64
+ const effort = findAcpEffortConfig(configOptions);
65
+ if (effort === undefined) return "unknown" as const;
66
+ return {
67
+ optionDescriptors: [
68
+ {
69
+ id: descriptor.id,
70
+ label: effort.label || descriptor.fallbackLabel,
71
+ type: "select" as const,
72
+ options: effort.choices.map((choice) => ({
73
+ id: choice.value,
74
+ label: choice.label,
75
+ ...(choice.description === undefined ? {} : { description: choice.description }),
76
+ ...(choice.isDefault === true ? { isDefault: true } : {}),
77
+ })),
78
+ },
79
+ ],
80
+ };
81
+ }