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,492 @@
1
+ import { NativeHistoryCursorError, NativeHistoryPendingError } from "./historyErrors.ts";
2
+ export { waitForJsonlHistory } from "./historyWaiting.ts";
3
+ // @effect-diagnostics nodeBuiltinImport:off - 原生执行器的文件读取边界;不运行 CLI,不写入转录。
4
+ import * as NodeFS from "node:fs";
5
+ import * as NodePath from "node:path";
6
+ import type {
7
+ ExecutorHistoryCursor,
8
+ ExecutorHistoryFrame,
9
+ ExecutorHistoryPageOptions,
10
+ ExecutorHistorySource,
11
+ ExecutorLiveHistoryItem,
12
+ ExecutorLiveHistoryPage,
13
+ } from "@ycodium-ai/plugin-api/executor";
14
+ import {
15
+ historyBoundary,
16
+ historyBytes,
17
+ historyIdentity,
18
+ historyLines,
19
+ type LineRange,
20
+ } from "./historyFile.ts";
21
+ import {
22
+ createHistoryRecordAccumulator,
23
+ historyRecordWindows,
24
+ inspectHistoryRecord,
25
+ verifyHistoryRecord,
26
+ type HistoryLayout,
27
+ type RecordInfo,
28
+ } from "./historyRecord.ts";
29
+ export type { HistoryLayout } from "./historyRecord.ts";
30
+
31
+ type Position = { e: string; p: number; k: number; o: number; h: string };
32
+ const RECORD_CACHE_LIMIT = 32;
33
+ const TEXT_CACHE_CHARS = 262_144;
34
+ type CachedRecord = { info: RecordInfo; text?: string; mode?: "raw" | "message" };
35
+ const recordCache = new Map<string, CachedRecord>();
36
+ const headCache = new Map<string, ExecutorHistoryCursor>();
37
+ const cacheKey = (
38
+ path: string,
39
+ identity: { identity: string; size: number; mtimeMs: number; ctimeMs: number },
40
+ ) => `${path}\0${identity.identity}\0${identity.size}\0${identity.mtimeMs}\0${identity.ctimeMs}`;
41
+ const remember = <T>(cache: Map<string, T>, key: string, value: T, limit = RECORD_CACHE_LIMIT) => {
42
+ cache.delete(key);
43
+ cache.set(key, value);
44
+ if (cache.size > limit) cache.delete(cache.keys().next().value!);
45
+ return value;
46
+ };
47
+ const encode = (position: Position) => Buffer.from(JSON.stringify(position)).toString("base64url");
48
+ const decode = (value: string): Position => {
49
+ let p: Partial<Position>;
50
+ try {
51
+ p = JSON.parse(Buffer.from(value, "base64url").toString("utf8")) as Partial<Position>;
52
+ } catch {
53
+ throw new NativeHistoryCursorError();
54
+ }
55
+ if (
56
+ !p ||
57
+ typeof p.e !== "string" ||
58
+ typeof p.h !== "string" ||
59
+ ![p.p, p.k, p.o].every((n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0)
60
+ )
61
+ throw new NativeHistoryCursorError();
62
+ return p as Position;
63
+ };
64
+ const width = (n: number) => String(n).padStart(20, "0");
65
+ const high = (n: number) => n >= 0xd800 && n <= 0xdbff;
66
+ const low = (n: number) => n >= 0xdc00 && n <= 0xdfff;
67
+ const totalOf = (info: RecordInfo, index: number) =>
68
+ info.items[index]!.text === "raw" ? info.rawTotal : info.messageTotal;
69
+
70
+ const nativeItem = (
71
+ identity: string,
72
+ info: RecordInfo,
73
+ index: number,
74
+ offset: number,
75
+ text: string,
76
+ ): ExecutorLiveHistoryItem => {
77
+ const { text: _mode, ...item } = info.items[index]!;
78
+ const total = totalOf(info, index);
79
+ const position = { e: identity, p: info.range.start, k: index, h: info.hash };
80
+ return {
81
+ ...item,
82
+ id: `${identity}:${info.range.start}:${index}`,
83
+ orderKey: `${width(info.range.start)}:${width(index)}`,
84
+ beforeCursor: encode({ ...position, o: offset }),
85
+ afterCursor: encode({ ...position, o: offset + text.length }),
86
+ text,
87
+ textWindow: {
88
+ offset,
89
+ returned: text.length,
90
+ total,
91
+ nextOffset: offset + text.length < total ? offset + text.length : null,
92
+ },
93
+ };
94
+ };
95
+
96
+ const readWindow = async (
97
+ path: string,
98
+ info: RecordInfo,
99
+ index: number,
100
+ from: number,
101
+ until: number,
102
+ layout: HistoryLayout,
103
+ signal: AbortSignal,
104
+ cached: CachedRecord,
105
+ ) => {
106
+ const base = Math.max(0, from - 1);
107
+ const end = Math.min(totalOf(info, index), until + 1);
108
+ const mode = info.items[index]!.text;
109
+ if (cached.text === undefined && totalOf(info, index) <= TEXT_CACHE_CHARS) {
110
+ const parts: string[] = [];
111
+ for await (const window of historyRecordWindows(
112
+ path,
113
+ info,
114
+ mode,
115
+ 0,
116
+ totalOf(info, index),
117
+ 65_536,
118
+ layout,
119
+ signal,
120
+ ))
121
+ parts.push(window.text);
122
+ cached.text = parts.join("");
123
+ cached.mode = mode;
124
+ }
125
+ let text = cached.mode === mode ? (cached.text?.slice(base, end) ?? "") : "";
126
+ if (cached.mode !== mode) {
127
+ for await (const window of historyRecordWindows(
128
+ path,
129
+ info,
130
+ mode,
131
+ base,
132
+ end,
133
+ Math.max(2, end - base),
134
+ layout,
135
+ signal,
136
+ ))
137
+ text += window.text;
138
+ }
139
+ let startIndex = from - base;
140
+ let endIndex = until - base;
141
+ if (low(text.charCodeAt(startIndex)) && high(text.charCodeAt(startIndex - 1))) startIndex -= 1;
142
+ if (low(text.charCodeAt(endIndex)) && high(text.charCodeAt(endIndex - 1))) endIndex -= 1;
143
+ return { offset: base + startIndex, text: text.slice(startIndex, endIndex) };
144
+ };
145
+
146
+ /** 打开仅解析身份;page 不注册观察器,follow 被消费时才拥有一个目录观察器。 */
147
+ export async function openJsonlHistory(
148
+ path: string,
149
+ layout: HistoryLayout,
150
+ signal?: AbortSignal,
151
+ ): Promise<ExecutorHistorySource> {
152
+ const controller = new AbortController();
153
+ const combined = (next?: AbortSignal) =>
154
+ AbortSignal.any([controller.signal, ...(signal ? [signal] : []), ...(next ? [next] : [])]);
155
+ let verified: Awaited<ReturnType<typeof historyIdentity>> | undefined;
156
+ const verify = async (readSignal: AbortSignal) => {
157
+ const identity = await historyIdentity(path);
158
+ if (
159
+ verified?.identity === identity.identity &&
160
+ verified.size === identity.size &&
161
+ verified.mtimeMs === identity.mtimeMs &&
162
+ verified.ctimeMs === identity.ctimeMs
163
+ )
164
+ return identity;
165
+ let checked = 0;
166
+ for await (const range of historyLines(path, 0, identity.size, false, readSignal)) {
167
+ if (await verifyHistoryRecord(path, range, layout, readSignal)) {
168
+ verified = identity;
169
+ return identity;
170
+ }
171
+ if (++checked >= 100) break;
172
+ }
173
+ throw new NativeHistoryPendingError();
174
+ };
175
+ await verify(combined());
176
+ const active = new Set<Promise<unknown>>();
177
+ const iterators = new Set<AsyncGenerator<ExecutorHistoryFrame>>();
178
+ const tracked = <T>(promise: Promise<T>) => {
179
+ active.add(promise);
180
+ void promise.finally(() => active.delete(promise)).catch(() => undefined);
181
+ return promise;
182
+ };
183
+
184
+ const inspect = async (
185
+ range: LineRange,
186
+ identity: { identity: string; size: number; mtimeMs: number; ctimeMs: number },
187
+ readSignal: AbortSignal,
188
+ ) => {
189
+ const key = `${cacheKey(path, identity)}\0${range.start}`;
190
+ const cached = recordCache.get(key);
191
+ if (cached?.info.range.end === range.end) return cached;
192
+ const info = await inspectHistoryRecord(path, range, layout, readSignal);
193
+ return info === undefined ? undefined : remember(recordCache, key, { info });
194
+ };
195
+ const head = async (
196
+ identity: { identity: string; size: number; mtimeMs: number; ctimeMs: number },
197
+ readSignal: AbortSignal,
198
+ ) => {
199
+ const key = cacheKey(path, identity);
200
+ const saved = headCache.get(key);
201
+ if (saved !== undefined) return saved;
202
+ for await (const range of historyLines(path, 0, identity.size, true, readSignal)) {
203
+ const info = await inspect(range, identity, readSignal);
204
+ if (info !== undefined)
205
+ return remember(
206
+ headCache,
207
+ key,
208
+ await historyBoundary(path, identity.identity, range.commit, readSignal),
209
+ );
210
+ }
211
+ return remember(headCache, key, await historyBoundary(path, identity.identity, 0, readSignal));
212
+ };
213
+ const page = async (input: ExecutorHistoryPageOptions): Promise<ExecutorLiveHistoryPage> => {
214
+ const readSignal = combined(input.signal);
215
+ readSignal.throwIfAborted();
216
+ if (input.before !== undefined && input.after !== undefined)
217
+ throw new NativeHistoryCursorError();
218
+ if (input.fromStart && input.before !== undefined) throw new NativeHistoryCursorError();
219
+ const identity = await verify(readSignal);
220
+ const position =
221
+ input.before !== undefined
222
+ ? decode(input.before)
223
+ : input.after !== undefined
224
+ ? decode(input.after)
225
+ : undefined;
226
+ if (position !== undefined && (position.e !== identity.identity || position.p > identity.size))
227
+ throw new NativeHistoryCursorError();
228
+ const backwards = input.after === undefined && input.fromStart !== true;
229
+ const initialRange =
230
+ position === undefined
231
+ ? undefined
232
+ : await (async () => {
233
+ const cached = recordCache.get(`${cacheKey(path, identity)}\0${position.p}`);
234
+ if (cached !== undefined) return cached.info.range;
235
+ for await (const range of historyLines(
236
+ path,
237
+ position.p,
238
+ identity.size,
239
+ false,
240
+ readSignal,
241
+ ))
242
+ return range;
243
+ throw new NativeHistoryCursorError();
244
+ })();
245
+ const ranges = async function* (): AsyncGenerator<LineRange> {
246
+ if (initialRange !== undefined) yield initialRange;
247
+ yield* backwards
248
+ ? historyLines(path, 0, position?.p ?? identity.size, true, readSignal)
249
+ : historyLines(path, initialRange?.commit ?? 0, identity.size, false, readSignal);
250
+ };
251
+ const items: ExecutorLiveHistoryItem[] = [];
252
+ let budget = Math.min(12_000, input.textLimit ?? 12_000);
253
+ const limit = Math.min(50, input.limit ?? 20);
254
+ let more = false;
255
+ for await (const range of ranges()) {
256
+ if (items.length >= limit || budget < 2) {
257
+ more = true;
258
+ break;
259
+ }
260
+ const cached = await inspect(range, identity, readSignal);
261
+ if (cached === undefined) continue;
262
+ const info = cached.info;
263
+ const first = position !== undefined && range.start === position.p;
264
+ if (
265
+ first &&
266
+ (position.h !== info.hash ||
267
+ position.k >= info.items.length ||
268
+ position.o > totalOf(info, position.k))
269
+ )
270
+ throw new NativeHistoryCursorError();
271
+ const indices = Array.from({ length: info.items.length }, (_, index) => index);
272
+ if (backwards) indices.reverse();
273
+ for (const index of indices) {
274
+ if (first && (backwards ? index > position.k : index < position.k)) continue;
275
+ const total = totalOf(info, index);
276
+ if (first && index === position.k && total === 0) continue;
277
+ const boundary = first && index === position.k ? position.o : backwards ? total : 0;
278
+ if (total > 0 && (backwards ? boundary === 0 : boundary === total)) continue;
279
+ if (items.length >= limit || budget < 2) {
280
+ more = true;
281
+ break;
282
+ }
283
+ const from = backwards ? Math.max(0, boundary - budget) : boundary;
284
+ const until = backwards ? boundary : Math.min(total, from + budget);
285
+ const window = await readWindow(path, info, index, from, until, layout, readSignal, cached);
286
+ const item = nativeItem(identity.identity, info, index, window.offset, window.text);
287
+ if (backwards) items.unshift(item);
288
+ else items.push(item);
289
+ budget -= window.text.length;
290
+ if (backwards ? window.offset > 0 : window.offset + window.text.length < total) {
291
+ more = true;
292
+ break;
293
+ }
294
+ }
295
+ if (more) break;
296
+ }
297
+ const liveCursor = await head(identity, readSignal);
298
+ return {
299
+ sourceEpoch: identity.identity,
300
+ items,
301
+ olderCursor:
302
+ items.length === 0
303
+ ? null
304
+ : backwards && !more && position === undefined
305
+ ? null
306
+ : items[0]!.beforeCursor,
307
+ newerCursor:
308
+ items.length === 0
309
+ ? null
310
+ : !backwards && !more
311
+ ? null
312
+ : backwards
313
+ ? input.before !== undefined
314
+ ? items.at(-1)!.afterCursor
315
+ : null
316
+ : more
317
+ ? items.at(-1)!.afterCursor
318
+ : null,
319
+ liveCursor,
320
+ };
321
+ };
322
+
323
+ const follow = (
324
+ input: Omit<ExecutorHistoryPageOptions, "before" | "after"> & {
325
+ readonly after?: ExecutorHistoryCursor;
326
+ },
327
+ ) => {
328
+ let iterator: AsyncGenerator<ExecutorHistoryFrame> | undefined;
329
+ iterator = (async function* () {
330
+ const readSignal = combined(input.signal);
331
+ let dirty = true;
332
+ let wake: (() => void) | undefined;
333
+ let failure: unknown;
334
+ const notify = () => {
335
+ dirty = true;
336
+ wake?.();
337
+ wake = undefined;
338
+ };
339
+ const watcher = NodeFS.watch(
340
+ NodePath.dirname(path),
341
+ { signal: readSignal },
342
+ (_event, file) => {
343
+ if (file == null || String(file) === NodePath.basename(path)) notify();
344
+ },
345
+ );
346
+ watcher.on("error", (error) => {
347
+ failure = error;
348
+ notify();
349
+ });
350
+ const abort = () => notify();
351
+ readSignal.addEventListener("abort", abort, { once: true });
352
+ let committed = input.after;
353
+ const reset = async () =>
354
+ page({
355
+ ...(input.limit === undefined ? {} : { limit: input.limit }),
356
+ ...(input.textLimit === undefined ? {} : { textLimit: input.textLimit }),
357
+ signal: readSignal,
358
+ });
359
+ try {
360
+ let identity = await verify(readSignal);
361
+ const boundary =
362
+ committed !== undefined && committed.sequence <= identity.size
363
+ ? await historyBoundary(path, identity.identity, committed.sequence, readSignal)
364
+ : undefined;
365
+ if (
366
+ committed === undefined ||
367
+ boundary?.epoch !== committed.epoch ||
368
+ identity.size - committed.sequence > 1_048_576
369
+ ) {
370
+ const value = await reset();
371
+ committed = value.liveCursor;
372
+ yield { _tag: "snapshot", cursor: committed, value };
373
+ }
374
+ let synchronized = false;
375
+ let scanned = committed!.sequence;
376
+ let pendingStart = scanned;
377
+ let accumulator = createHistoryRecordAccumulator(layout);
378
+ const appended = async function* (end: number) {
379
+ for await (const bytes of historyBytes(path, scanned, end, readSignal)) {
380
+ let from = 0;
381
+ const chunkStart = scanned;
382
+ for (let index = 0; index < bytes.length; index += 1) {
383
+ if (bytes[index] !== 10) continue;
384
+ accumulator.write(bytes.subarray(from, index));
385
+ const at = chunkStart + index;
386
+ const info =
387
+ at > pendingStart
388
+ ? accumulator.finish({
389
+ start: pendingStart,
390
+ end: at,
391
+ commit: at + 1,
392
+ terminated: true,
393
+ })
394
+ : undefined;
395
+ pendingStart = at + 1;
396
+ accumulator = createHistoryRecordAccumulator(layout);
397
+ from = index + 1;
398
+ if (info !== undefined) yield info;
399
+ }
400
+ accumulator.write(bytes.subarray(from));
401
+ scanned += bytes.length;
402
+ }
403
+ };
404
+ while (true) {
405
+ readSignal.throwIfAborted();
406
+ if (failure !== undefined) throw failure;
407
+ if (!dirty)
408
+ await new Promise<void>((resolve) => {
409
+ wake = resolve;
410
+ });
411
+ readSignal.throwIfAborted();
412
+ dirty = false;
413
+ identity = await historyIdentity(path);
414
+ const current = committed!;
415
+ const valid =
416
+ scanned <= identity.size &&
417
+ current.sequence <= identity.size &&
418
+ (await historyBoundary(path, identity.identity, current.sequence, readSignal)).epoch ===
419
+ current.epoch;
420
+ if (!valid) {
421
+ const value = await reset();
422
+ synchronized = false;
423
+ committed = value.liveCursor;
424
+ scanned = committed.sequence;
425
+ pendingStart = scanned;
426
+ accumulator = createHistoryRecordAccumulator(layout);
427
+ yield { _tag: "snapshot", cursor: committed, value };
428
+ } else {
429
+ for await (const info of appended(identity.size)) {
430
+ const next = await historyBoundary(
431
+ path,
432
+ identity.identity,
433
+ info.range.commit,
434
+ readSignal,
435
+ );
436
+ for (let index = 0; index < info.items.length; index += 1) {
437
+ const total = totalOf(info, index);
438
+ if (total === 0) {
439
+ yield {
440
+ _tag: "delta",
441
+ cursor: index === info.items.length - 1 ? next : committed!,
442
+ items: [nativeItem(identity.identity, info, index, 0, "")],
443
+ };
444
+ continue;
445
+ }
446
+ for await (const window of historyRecordWindows(
447
+ path,
448
+ info,
449
+ info.items[index]!.text,
450
+ 0,
451
+ total,
452
+ Math.min(12_000, input.textLimit ?? 12_000),
453
+ layout,
454
+ readSignal,
455
+ )) {
456
+ const done =
457
+ index === info.items.length - 1 && window.offset + window.text.length === total;
458
+ yield {
459
+ _tag: "delta",
460
+ cursor: done ? next : committed!,
461
+ items: [nativeItem(identity.identity, info, index, window.offset, window.text)],
462
+ };
463
+ }
464
+ }
465
+ committed = next;
466
+ }
467
+ }
468
+ if (!synchronized) {
469
+ synchronized = true;
470
+ yield { _tag: "synchronized" };
471
+ }
472
+ }
473
+ } finally {
474
+ watcher.close();
475
+ readSignal.removeEventListener("abort", abort);
476
+ wake?.();
477
+ if (iterator !== undefined) iterators.delete(iterator);
478
+ }
479
+ })();
480
+ iterators.add(iterator);
481
+ return iterator;
482
+ };
483
+ return {
484
+ page: (input) => tracked(page(input)),
485
+ follow,
486
+ close: async () => {
487
+ controller.abort();
488
+ await Promise.all([...iterators].map((iterator) => iterator.return(undefined)));
489
+ await Promise.allSettled(active);
490
+ },
491
+ };
492
+ }
@@ -0,0 +1,6 @@
1
+ export class NativeHistoryCursorError extends Error {
2
+ override readonly name = "NativeHistoryCursorError";
3
+ }
4
+ export class NativeHistoryPendingError extends Error {
5
+ override readonly name = "NativeHistoryPendingError";
6
+ }
@@ -0,0 +1,139 @@
1
+ // @effect-diagnostics nodeBuiltinImport:off - 执行器只读文件适配器,不依赖宿主 Effect。
2
+ import * as NodeFSP from "node:fs/promises";
3
+ import * as NodeCrypto from "node:crypto";
4
+ const HISTORY_READ_BYTES = 65_536;
5
+ export type LineRange = {
6
+ readonly start: number;
7
+ readonly end: number;
8
+ readonly commit: number;
9
+ readonly terminated: boolean;
10
+ };
11
+
12
+ export async function* historyBytes(
13
+ path: string,
14
+ start: number,
15
+ end: number,
16
+ signal?: AbortSignal,
17
+ ) {
18
+ const file = await NodeFSP.open(path, "r");
19
+ try {
20
+ let offset = start;
21
+ while (offset < end) {
22
+ signal?.throwIfAborted();
23
+ const buffer = Buffer.allocUnsafe(Math.min(HISTORY_READ_BYTES, end - offset));
24
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, offset);
25
+ if (bytesRead === 0) throw new Error("Native history changed during a read.");
26
+ offset += bytesRead;
27
+ yield buffer.subarray(0, bytesRead);
28
+ }
29
+ } finally {
30
+ await file.close();
31
+ }
32
+ }
33
+
34
+ export async function* historyText(path: string, range: LineRange, signal?: AbortSignal) {
35
+ const decoder = new TextDecoder("utf-8", { fatal: true });
36
+ for await (const bytes of historyBytes(path, range.start, range.end, signal)) {
37
+ const text = decoder.decode(bytes, { stream: true });
38
+ if (text) yield text;
39
+ }
40
+ const last = decoder.decode();
41
+ if (last) yield last;
42
+ }
43
+
44
+ export async function* historyLines(
45
+ path: string,
46
+ start: number,
47
+ end: number,
48
+ backwards: boolean,
49
+ signal?: AbortSignal,
50
+ ): AsyncGenerator<LineRange> {
51
+ if (!backwards) {
52
+ let lineStart = start;
53
+ let offset = start;
54
+ for await (const bytes of historyBytes(path, start, end, signal)) {
55
+ for (let index = 0; index < bytes.length; index += 1) {
56
+ if (bytes[index] !== 10) continue;
57
+ const lineEnd = offset + index;
58
+ if (lineEnd > lineStart)
59
+ yield { start: lineStart, end: lineEnd, commit: lineEnd + 1, terminated: true };
60
+ lineStart = lineEnd + 1;
61
+ }
62
+ offset += bytes.length;
63
+ }
64
+ if (lineStart < end) yield { start: lineStart, end, commit: end, terminated: false };
65
+ return;
66
+ }
67
+ const file = await NodeFSP.open(path, "r");
68
+ try {
69
+ let scan = end;
70
+ let lineEnd = end;
71
+ let terminated = false;
72
+ while (scan > start) {
73
+ signal?.throwIfAborted();
74
+ const from = Math.max(start, scan - HISTORY_READ_BYTES);
75
+ const buffer = Buffer.allocUnsafe(scan - from);
76
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, from);
77
+ if (bytesRead !== buffer.length) throw new Error("Native history changed during a read.");
78
+ for (let index = buffer.length - 1; index >= 0; index -= 1) {
79
+ if (buffer[index] !== 10) continue;
80
+ const at = from + index;
81
+ if (at + 1 < lineEnd)
82
+ yield { start: at + 1, end: lineEnd, commit: lineEnd + (terminated ? 1 : 0), terminated };
83
+ lineEnd = at;
84
+ terminated = true;
85
+ }
86
+ scan = from;
87
+ }
88
+ if (lineEnd > start)
89
+ yield { start, end: lineEnd, commit: lineEnd + (terminated ? 1 : 0), terminated };
90
+ } finally {
91
+ await file.close();
92
+ }
93
+ }
94
+
95
+ export const historyIdentity = async (path: string) => {
96
+ const stat = await NodeFSP.stat(path);
97
+ return {
98
+ size: stat.size,
99
+ mtimeMs: stat.mtimeMs,
100
+ ctimeMs: stat.ctimeMs,
101
+ identity: NodeCrypto.createHash("sha256")
102
+ .update(`${path}/${stat.dev}/${stat.ino}/${stat.birthtimeMs}`)
103
+ .digest("hex"),
104
+ };
105
+ };
106
+
107
+ /** 续接时抽样已提交前缀,覆盖头、中段和尾段;每次文件通知最多读固定大小。 */
108
+ const historyCommittedFingerprint = async (
109
+ path: string,
110
+ sequence: number,
111
+ signal?: AbortSignal,
112
+ ) => {
113
+ const hash = NodeCrypto.createHash("sha256");
114
+ const starts = [
115
+ 0,
116
+ Math.max(0, Math.floor(sequence / 3) - 512),
117
+ Math.max(0, Math.floor((sequence * 2) / 3) - 512),
118
+ Math.max(0, sequence - 1_024),
119
+ ];
120
+ for (const start of new Set(starts)) {
121
+ const end = Math.min(sequence, start + 1_024);
122
+ hash.update(`${start}:${end}:`);
123
+ for await (const bytes of historyBytes(path, start, end, signal)) hash.update(bytes);
124
+ }
125
+ return hash.digest("hex");
126
+ };
127
+
128
+ export const historyBoundary = async (
129
+ path: string,
130
+ identity: string,
131
+ sequence: number,
132
+ signal?: AbortSignal,
133
+ ) => {
134
+ const hash = NodeCrypto.createHash("sha256");
135
+ for await (const bytes of historyBytes(path, Math.max(0, sequence - 128), sequence, signal))
136
+ hash.update(bytes);
137
+ hash.update(await historyCommittedFingerprint(path, sequence, signal));
138
+ return { epoch: `${identity}.${hash.digest("hex")}`, sequence };
139
+ };