clanka 0.25.2 → 0.26.0

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 (55) hide show
  1. package/dist/Acp.d.ts +5 -37
  2. package/dist/Acp.d.ts.map +1 -1
  3. package/dist/Acp.js +33 -48
  4. package/dist/Acp.js.map +1 -1
  5. package/dist/Acp.test.js +62 -1
  6. package/dist/Acp.test.js.map +1 -1
  7. package/dist/AcpImage.test.js +3 -2
  8. package/dist/AcpImage.test.js.map +1 -1
  9. package/dist/AcpSessionStore.d.ts +114 -0
  10. package/dist/AcpSessionStore.d.ts.map +1 -0
  11. package/dist/AcpSessionStore.js +327 -0
  12. package/dist/AcpSessionStore.js.map +1 -0
  13. package/dist/AcpSessionStore.test.d.ts +2 -0
  14. package/dist/AcpSessionStore.test.d.ts.map +1 -0
  15. package/dist/AcpSessionStore.test.js +135 -0
  16. package/dist/AcpSessionStore.test.js.map +1 -0
  17. package/dist/Agent.d.ts.map +1 -1
  18. package/dist/Agent.js +5 -1
  19. package/dist/Agent.js.map +1 -1
  20. package/dist/Agent.test.js +20 -0
  21. package/dist/Agent.test.js.map +1 -1
  22. package/dist/ScriptFormatting.d.ts +3 -0
  23. package/dist/ScriptFormatting.d.ts.map +1 -0
  24. package/dist/ScriptFormatting.js +61 -0
  25. package/dist/ScriptFormatting.js.map +1 -0
  26. package/dist/ScriptFormatting.test.d.ts +2 -0
  27. package/dist/ScriptFormatting.test.d.ts.map +1 -0
  28. package/dist/ScriptFormatting.test.js +60 -0
  29. package/dist/ScriptFormatting.test.js.map +1 -0
  30. package/dist/bin/{AiError-CsvdOsKR.mjs → AiError-DBaKz35C.mjs} +2 -2
  31. package/dist/bin/{Latch-B3e9629m.mjs → Latch-DOdbsGMQ.mjs} +1 -1
  32. package/dist/bin/{McpClient-BCxZZgnA.mjs → McpClient-B-FFG6Pg.mjs} +1 -1
  33. package/dist/bin/{OutputFormatter-ByMjyBhe.mjs → OutputFormatter-DhhP2i-7.mjs} +2 -2
  34. package/dist/bin/{Schema-BfUmMefy.mjs → Schema-CFdSO6iH.mjs} +11 -1
  35. package/dist/bin/{SemanticSearch-DMzIsoZb.mjs → SemanticSearch-C3a7LAQr.mjs} +6 -6
  36. package/dist/bin/cli.mjs +392 -143
  37. package/dist/bin/{upgrade-t590zYhO.mjs → upgrade-C4aOEWJH.mjs} +2 -2
  38. package/dist/cli.js +10 -3
  39. package/dist/cli.js.map +1 -1
  40. package/dist/index.d.ts +4 -0
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +4 -0
  43. package/dist/index.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/Acp.test.ts +120 -1
  46. package/src/Acp.ts +41 -55
  47. package/src/AcpImage.test.ts +7 -2
  48. package/src/AcpSessionStore.test.ts +220 -0
  49. package/src/AcpSessionStore.ts +455 -0
  50. package/src/Agent.test.ts +36 -0
  51. package/src/Agent.ts +5 -1
  52. package/src/ScriptFormatting.test.ts +66 -0
  53. package/src/ScriptFormatting.ts +57 -0
  54. package/src/cli.ts +20 -9
  55. package/src/index.ts +5 -0
@@ -0,0 +1,220 @@
1
+ import { assert, describe, it } from "@effect/vitest"
2
+ import * as NodeServices from "@effect/platform-node/NodeServices"
3
+ import * as Context from "effect/Context"
4
+ import * as Deferred from "effect/Deferred"
5
+ import * as Effect from "effect/Effect"
6
+ import * as FileSystem from "effect/FileSystem"
7
+ import * as Layer from "effect/Layer"
8
+ import * as Option from "effect/Option"
9
+ import * as Path from "effect/Path"
10
+ import * as Prompt from "effect/ai/Prompt"
11
+ import * as AcpSessionStore from "./AcpSessionStore.ts"
12
+
13
+ const message = (role: "user" | "assistant", text: string) =>
14
+ Prompt.makeMessage(role, {
15
+ content: [Prompt.makePart("text", { text })],
16
+ })
17
+
18
+ const record = (
19
+ messages: ReadonlyArray<Prompt.Message>,
20
+ model = "test:model",
21
+ ) =>
22
+ new AcpSessionStore.SessionRecord({
23
+ cwd: "/tmp",
24
+ model,
25
+ thoughtLevel: "medium",
26
+ fastMode: false,
27
+ history: Prompt.fromMessages(messages),
28
+ })
29
+
30
+ const texts = (stored: Option.Option<AcpSessionStore.SessionRecord>) =>
31
+ Option.getOrThrow(stored).history.content.map((message) => {
32
+ const [part] = message.content
33
+ return typeof part === "object" && part.type === "text"
34
+ ? part.text
35
+ : undefined
36
+ })
37
+
38
+ // Each call is a new process: it knows nothing about the files yet.
39
+ const openStore = (directory: string) =>
40
+ Layer.build(AcpSessionStore.layerFileSystem(directory)).pipe(
41
+ Effect.map((context) =>
42
+ Context.get(context, AcpSessionStore.AcpSessionStore),
43
+ ),
44
+ )
45
+
46
+ const withDirectory = <A, E, R>(
47
+ f: (
48
+ directory: string,
49
+ file: (sessionId: string) => string,
50
+ ) => Effect.Effect<A, E, R>,
51
+ ) =>
52
+ Effect.gen(function* () {
53
+ const fs = yield* FileSystem.FileSystem
54
+ const path = yield* Path.Path
55
+ const directory = yield* fs.makeTempDirectoryScoped()
56
+ return yield* f(directory, (sessionId) =>
57
+ path.join(directory, `${sessionId}.jsonl`),
58
+ )
59
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))
60
+
61
+ const lines = Effect.fnUntraced(function* (file: string) {
62
+ const fs = yield* FileSystem.FileSystem
63
+ const text = yield* fs.readFileString(file)
64
+ return text.split("\n").filter((line) => line !== "")
65
+ })
66
+
67
+ describe("AcpSessionStore.layerFileSystem", () => {
68
+ it.effect(
69
+ "appends what each write adds and rewrites a replaced history",
70
+ () =>
71
+ withDirectory(
72
+ Effect.fnUntraced(function* (directory, file) {
73
+ const hello = message("user", "hello")
74
+ const hi = message("assistant", "hi")
75
+ const store = yield* openStore(directory)
76
+ yield* store.set("s", record([hello]))
77
+ yield* store.set("s", record([hello, hi], "other:model"))
78
+ const [first, second] = yield* lines(file("s"))
79
+ assert.include(first, '"Snapshot"')
80
+ assert.include(second, '"Update"')
81
+ assert.notInclude(second, "hello")
82
+
83
+ const loaded = yield* (yield* openStore(directory)).get("s")
84
+ assert.deepStrictEqual(texts(loaded), ["hello", "hi"])
85
+ assert.strictEqual(Option.getOrThrow(loaded).model, "other:model")
86
+
87
+ yield* store.set("s", record([message("user", "summary")]))
88
+ assert.strictEqual((yield* lines(file("s"))).length, 1)
89
+ const compacted = yield* (yield* openStore(directory)).get("s")
90
+ assert.deepStrictEqual(texts(compacted), ["summary"])
91
+ }),
92
+ ),
93
+ )
94
+
95
+ it.effect(
96
+ "drops an interrupted append and replaces the file on the next write",
97
+ () =>
98
+ withDirectory(
99
+ Effect.fnUntraced(function* (directory, file) {
100
+ const fs = yield* FileSystem.FileSystem
101
+ const hello = message("user", "hello")
102
+ const store = yield* openStore(directory)
103
+ yield* store.set("s", record([hello]))
104
+ yield* store.set("s", record([hello, message("assistant", "lost")]))
105
+ // A kill in the middle of the second line.
106
+ const text = yield* fs.readFileString(file("s"))
107
+ yield* fs.writeFileString(
108
+ file("s"),
109
+ text.slice(0, text.indexOf("\n") + 20),
110
+ )
111
+
112
+ const next = yield* openStore(directory)
113
+ const loaded = yield* next.get("s")
114
+ assert.deepStrictEqual(texts(loaded), ["hello"])
115
+ const history = Option.getOrThrow(loaded).history.content
116
+ yield* next.set("s", record([...history, message("user", "again")]))
117
+
118
+ const reloaded = yield* (yield* openStore(directory)).get("s")
119
+ assert.deepStrictEqual(texts(reloaded), ["hello", "again"])
120
+ }),
121
+ ),
122
+ )
123
+
124
+ it.effect(
125
+ "starts over from a file replaced by another process, even at the same size",
126
+ () =>
127
+ withDirectory(
128
+ Effect.fnUntraced(function* (directory) {
129
+ const a = yield* openStore(directory)
130
+ yield* a.set("s", record([message("user", "old")]))
131
+ const b = yield* openStore(directory)
132
+ const stale = Option.getOrThrow(yield* b.get("s")).history.content
133
+ yield* a.set("s", record([message("user", "new")]))
134
+ yield* b.set("s", record([...stale, message("user", "tail")]))
135
+
136
+ const loaded = yield* (yield* openStore(directory)).get("s")
137
+ assert.deepStrictEqual(texts(loaded), ["old", "tail"])
138
+ }),
139
+ ),
140
+ )
141
+
142
+ it.effect("stores a record again after another process replaced it", () =>
143
+ withDirectory(
144
+ Effect.fnUntraced(function* (directory) {
145
+ const a = yield* openStore(directory)
146
+ const first = record([message("user", "A")])
147
+ yield* a.set("s", first)
148
+ yield* (yield* openStore(directory)).set(
149
+ "s",
150
+ record([message("user", "B")]),
151
+ )
152
+ yield* a.set("s", first)
153
+
154
+ const loaded = yield* (yield* openStore(directory)).get("s")
155
+ assert.deepStrictEqual(texts(loaded), ["A"])
156
+ }),
157
+ ),
158
+ )
159
+
160
+ it.effect("never combines the appends of two racing processes", () =>
161
+ withDirectory(
162
+ Effect.fnUntraced(function* (directory) {
163
+ const fs = yield* FileSystem.FileSystem
164
+ // Holds every append until both processes are about to append, so
165
+ // both have checked the file before either writes.
166
+ const bothChecked = yield* Deferred.make<void>()
167
+ let appends = 0
168
+ const racing = FileSystem.FileSystem.of({
169
+ ...fs,
170
+ open: (file, options) =>
171
+ Effect.map(
172
+ fs.open(file, options),
173
+ (handle) =>
174
+ new Proxy(handle, {
175
+ get: (target, key) =>
176
+ key === "writeAll"
177
+ ? (bytes: Uint8Array) =>
178
+ Effect.gen(function* () {
179
+ if (++appends === 2) {
180
+ yield* Deferred.succeed(bothChecked, undefined)
181
+ }
182
+ yield* Deferred.await(bothChecked)
183
+ return yield* target.writeAll(bytes)
184
+ })
185
+ : Reflect.get(target, key, target),
186
+ }),
187
+ ),
188
+ })
189
+ const base = [message("user", "base")]
190
+ yield* (yield* openStore(directory)).set("s", record(base))
191
+ const a = yield* openStore(directory).pipe(
192
+ Effect.provideService(FileSystem.FileSystem, racing),
193
+ )
194
+ const b = yield* openStore(directory).pipe(
195
+ Effect.provideService(FileSystem.FileSystem, racing),
196
+ )
197
+ const fromA = Option.getOrThrow(yield* a.get("s")).history.content
198
+ const fromB = Option.getOrThrow(yield* b.get("s")).history.content
199
+ yield* Effect.all(
200
+ [
201
+ a.set("s", record([...fromA, message("user", "A")])),
202
+ b.set("s", record([...fromB, message("user", "B")])),
203
+ ],
204
+ { concurrency: 2 },
205
+ )
206
+ assert.strictEqual(appends, 2)
207
+
208
+ const loaded = texts(yield* (yield* openStore(directory)).get("s"))
209
+ assert.oneOf(loaded.join(), ["base,A", "base,B"])
210
+ // Each process sees the file changed, so its next write is whole.
211
+ yield* b.set(
212
+ "s",
213
+ record([...fromB, message("user", "B"), message("user", "C")]),
214
+ )
215
+ const next = yield* (yield* openStore(directory)).get("s")
216
+ assert.deepStrictEqual(texts(next), ["base", "B", "C"])
217
+ }),
218
+ ),
219
+ )
220
+ })
@@ -0,0 +1,455 @@
1
+ /** @effect-diagnostics schemaNumber:off */
2
+ /**
3
+ * Storage for ACP sessions, so `session/load` works across processes.
4
+ *
5
+ * `layerFileSystem` keeps each session in an append-only file. A write adds
6
+ * one line holding what changed since the last write, and rewrites the file
7
+ * only when the history was replaced, for example by compaction.
8
+ *
9
+ * @since 1.0.0
10
+ */
11
+ import * as Context from "effect/Context"
12
+ import * as Effect from "effect/Effect"
13
+ import * as FileSystem from "effect/FileSystem"
14
+ import * as Layer from "effect/Layer"
15
+ import * as Option from "effect/Option"
16
+ import * as Path from "effect/Path"
17
+ import type * as PlatformError from "effect/PlatformError"
18
+ import * as Schema from "effect/Schema"
19
+ import * as Semaphore from "effect/Semaphore"
20
+ import * as Prompt from "effect/ai/Prompt"
21
+ import * as KeyValueStore from "effect/persistence/KeyValueStore"
22
+ import * as AgentExecutor from "./AgentExecutor.ts"
23
+
24
+ /**
25
+ * Reasoning effort levels offered through the ACP `thought_level` config
26
+ * option.
27
+ *
28
+ * @since 1.0.0
29
+ * @category Models
30
+ */
31
+ export const ThoughtLevel = Schema.Literals([
32
+ "none",
33
+ "minimal",
34
+ "low",
35
+ "medium",
36
+ "high",
37
+ "xhigh",
38
+ "max",
39
+ ])
40
+
41
+ /**
42
+ * @since 1.0.0
43
+ * @category Models
44
+ */
45
+ export type ThoughtLevel = typeof ThoughtLevel.Type
46
+
47
+ /**
48
+ * @since 1.0.0
49
+ * @category Models
50
+ */
51
+ export class SessionRecord extends Schema.Class<SessionRecord>(
52
+ "clanka/Acp/SessionRecord",
53
+ )({
54
+ cwd: Schema.String,
55
+ model: Schema.String,
56
+ thoughtLevel: ThoughtLevel,
57
+ /**
58
+ * The session's fast mode setting. It is kept across model switches and
59
+ * applies while the session model supports fast mode.
60
+ */
61
+ fastMode: Schema.optionalKey(Schema.Boolean),
62
+ history: Prompt.Prompt,
63
+ /**
64
+ * The agent's executor environment, such as its working directory.
65
+ */
66
+ environment: Schema.optionalKey(AgentExecutor.ExecutionEnvironment),
67
+ }) {}
68
+
69
+ /**
70
+ * @since 1.0.0
71
+ * @category Errors
72
+ */
73
+ export class AcpSessionStoreError extends Schema.TaggedError<AcpSessionStoreError>()(
74
+ "AcpSessionStoreError",
75
+ {
76
+ message: Schema.String,
77
+ cause: Schema.optional(Schema.Defect()),
78
+ },
79
+ ) {}
80
+
81
+ /**
82
+ * @since 1.0.0
83
+ * @category Services
84
+ */
85
+ export class AcpSessionStore extends Context.Service<
86
+ AcpSessionStore,
87
+ {
88
+ readonly get: (
89
+ sessionId: string,
90
+ ) => Effect.Effect<Option.Option<SessionRecord>, AcpSessionStoreError>
91
+ readonly set: (
92
+ sessionId: string,
93
+ record: SessionRecord,
94
+ ) => Effect.Effect<void, AcpSessionStoreError>
95
+ }
96
+ >()("clanka/AcpSessionStore") {}
97
+
98
+ const keyValueStore = (kvs: KeyValueStore.KeyValueStore) => {
99
+ const store = KeyValueStore.toSchemaStore(
100
+ KeyValueStore.prefix(kvs, "session-"),
101
+ SessionRecord,
102
+ )
103
+ return AcpSessionStore.of({
104
+ get: (sessionId) =>
105
+ store
106
+ .get(sessionId)
107
+ .pipe(
108
+ Effect.mapError(
109
+ (cause) =>
110
+ new AcpSessionStoreError({ message: cause.message, cause }),
111
+ ),
112
+ ),
113
+ set: (sessionId, record) =>
114
+ store
115
+ .set(sessionId, record)
116
+ .pipe(
117
+ Effect.mapError(
118
+ (cause) =>
119
+ new AcpSessionStoreError({ message: cause.message, cause }),
120
+ ),
121
+ ),
122
+ })
123
+ }
124
+
125
+ /**
126
+ * Stores each session as one record under `session-<id>` in the
127
+ * KeyValueStore, rewritten whole on every write.
128
+ *
129
+ * @since 1.0.0
130
+ * @category Layers
131
+ */
132
+ export const layerKeyValueStore: Layer.Layer<
133
+ AcpSessionStore,
134
+ never,
135
+ KeyValueStore.KeyValueStore
136
+ > = Layer.effect(
137
+ AcpSessionStore,
138
+ Effect.gen(function* () {
139
+ return keyValueStore(yield* KeyValueStore.KeyValueStore)
140
+ }),
141
+ )
142
+
143
+ // One line of a session file. A file starts with a `Snapshot`, and each
144
+ // `Update` after it holds what changed since the line its `parent` names.
145
+ // Every line has a random `id`, encoded last so the end of a file names the
146
+ // line that ends it.
147
+ const Snapshot = Schema.TaggedStruct("Snapshot", {
148
+ record: SessionRecord,
149
+ id: Schema.String,
150
+ })
151
+
152
+ const Update = Schema.TaggedStruct("Update", {
153
+ cwd: Schema.optionalKey(Schema.String),
154
+ model: Schema.optionalKey(Schema.String),
155
+ thoughtLevel: Schema.optionalKey(ThoughtLevel),
156
+ fastMode: Schema.optionalKey(Schema.Boolean),
157
+ environment: Schema.optionalKey(AgentExecutor.ExecutionEnvironment),
158
+ /** Messages appended to the history. */
159
+ messages: Schema.optionalKey(Schema.Array(Prompt.Message)),
160
+ parent: Schema.String,
161
+ id: Schema.String,
162
+ })
163
+
164
+ const Entry = Schema.Union([Snapshot, Update])
165
+ type Entry = typeof Entry.Type
166
+
167
+ const EntryJson = Schema.fromJsonString(Schema.toCodecJson(Entry))
168
+ const decodeEntry = Schema.decodeExit(EntryJson)
169
+ const encodeEntry = Schema.encodeEffect(EntryJson)
170
+
171
+ const fieldKeys = [
172
+ "cwd",
173
+ "model",
174
+ "thoughtLevel",
175
+ "fastMode",
176
+ "environment",
177
+ ] as const
178
+
179
+ const applyUpdate = (
180
+ record: SessionRecord,
181
+ update: typeof Update.Type,
182
+ ): SessionRecord => {
183
+ const { _tag, messages, parent: _parent, id: _id, ...fields } = update
184
+ return new SessionRecord({
185
+ ...record,
186
+ ...fields,
187
+ history:
188
+ messages === undefined
189
+ ? record.history
190
+ : Prompt.fromMessages([...record.history.content, ...messages]),
191
+ })
192
+ }
193
+
194
+ // What changed from `previous` to `next`, or `undefined` when only a
195
+ // snapshot can express it: the history was not appended to, or a field was
196
+ // removed.
197
+ const diff = (
198
+ previous: SessionRecord,
199
+ next: SessionRecord,
200
+ ): Omit<typeof Update.Type, "_tag" | "parent" | "id"> | undefined => {
201
+ const before = previous.history.content
202
+ const after = next.history.content
203
+ if (
204
+ after.length < before.length ||
205
+ before.some((message, index) => after[index] !== message)
206
+ ) {
207
+ return undefined
208
+ }
209
+ const changes: Record<string, unknown> = {}
210
+ for (const key of fieldKeys) {
211
+ if (previous[key] === next[key]) continue
212
+ if (next[key] === undefined) return undefined
213
+ changes[key] = next[key]
214
+ }
215
+ if (after.length > before.length) {
216
+ changes.messages = after.slice(before.length)
217
+ }
218
+ return changes
219
+ }
220
+
221
+ const storeError =
222
+ (message: string) =>
223
+ (cause: unknown): AcpSessionStoreError =>
224
+ new AcpSessionStoreError({ message, cause })
225
+
226
+ const encodeLine = (entry: Entry) =>
227
+ encodeEntry(entry).pipe(
228
+ Effect.map((json) => encoder.encode(`${json}\n`)),
229
+ Effect.mapError(storeError("Failed to encode session")),
230
+ )
231
+
232
+ const newline = 0x0a
233
+ // Enough of the end of a file to hold the `id` of its last line.
234
+ const tailLength = 64
235
+ const encoder = new TextEncoder()
236
+ const decoder = new TextDecoder()
237
+
238
+ /**
239
+ * Stores each session in an append-only file, `<directory>/<id>.jsonl`.
240
+ *
241
+ * The first line is a snapshot of the session, and each later line holds the
242
+ * fields and history messages added to the line it names as its parent. A
243
+ * write that cannot be expressed as an addition, such as a compacted history,
244
+ * writes a new file and renames it over the old one.
245
+ *
246
+ * Loading follows the chain of lines from the snapshot and skips any line
247
+ * whose parent is not the line before it in the chain, so it always returns a
248
+ * record exactly as one `set` stored it, never a mix of two:
249
+ *
250
+ * - A process killed while appending can leave an incomplete last line, which
251
+ * loading ignores. The next write replaces the file.
252
+ * - Writes through one layer are serialized. Across layers and processes
253
+ * there is no lock, and only one process may write a session at a time, as
254
+ * when a client kills one process and loads the session in the next.
255
+ * - Every write first checks that the file is what this layer last read or
256
+ * wrote, and writes a whole snapshot when it is not. A process that takes
257
+ * over a session therefore replaces whatever an earlier owner wrote after
258
+ * it last loaded the session.
259
+ * - Writes from processes that do overlap are not ordered: which one a later
260
+ * load returns is unspecified, and the others can be lost. The next write
261
+ * from each of them is a snapshot.
262
+ *
263
+ * @since 1.0.0
264
+ * @category Layers
265
+ */
266
+ export const layerFileSystem = (
267
+ directory: string,
268
+ ): Layer.Layer<
269
+ AcpSessionStore,
270
+ PlatformError.PlatformError,
271
+ FileSystem.FileSystem | Path.Path
272
+ > =>
273
+ Layer.effect(
274
+ AcpSessionStore,
275
+ Effect.gen(function* () {
276
+ const fs = yield* FileSystem.FileSystem
277
+ const path = yield* Path.Path
278
+ yield* fs.makeDirectory(directory, { recursive: true })
279
+ const semaphore = yield* Semaphore.make(1)
280
+
281
+ // What this layer last read or wrote in each file: the record its chain
282
+ // adds up to, the id of the chain's last line, and the file's length and
283
+ // last bytes. A file that is no longer exactly this gets a snapshot.
284
+ const files = new Map<
285
+ string,
286
+ {
287
+ readonly record: SessionRecord
288
+ readonly id: string
289
+ readonly size: number
290
+ readonly tail: Uint8Array
291
+ }
292
+ >()
293
+
294
+ const fileFor = (sessionId: string) =>
295
+ path.join(directory, `${encodeURIComponent(sessionId)}.jsonl`)
296
+
297
+ const read = Effect.fnUntraced(function* (sessionId: string) {
298
+ const file = fileFor(sessionId)
299
+ files.delete(sessionId)
300
+ const result = yield* fs.readFile(file).pipe(
301
+ Effect.asSome,
302
+ Effect.catchReason(
303
+ "PlatformError",
304
+ "NotFound",
305
+ () => Effect.succeedNone,
306
+ ),
307
+ Effect.mapError(storeError(`Failed to read session ${sessionId}`)),
308
+ )
309
+ if (Option.isNone(result)) return Option.none()
310
+ const bytes = result.value
311
+ let record: SessionRecord | undefined
312
+ let id = ""
313
+ let start = 0
314
+ while (start < bytes.length) {
315
+ const end = bytes.indexOf(newline, start)
316
+ // An incomplete last line: the append writing it was cut short.
317
+ if (end === -1) break
318
+ const entry = decodeEntry(decoder.decode(bytes.subarray(start, end)))
319
+ start = end + 1
320
+ if (entry._tag === "Failure") continue
321
+ const line = entry.value
322
+ if (line._tag === "Snapshot") {
323
+ if (record !== undefined) continue
324
+ record = line.record
325
+ } else {
326
+ // Written by a process that did not know the file ended here.
327
+ if (record === undefined || line.parent !== id) continue
328
+ record = applyUpdate(record, line)
329
+ }
330
+ id = line.id
331
+ }
332
+ if (record === undefined) {
333
+ return yield* new AcpSessionStoreError({
334
+ message: `Session file for ${sessionId} does not start with a snapshot`,
335
+ })
336
+ }
337
+ if (start < bytes.length) {
338
+ yield* Effect.logWarning(
339
+ "Ignoring an incomplete end of an ACP session file",
340
+ ).pipe(Effect.annotateLogs({ sessionId, file }))
341
+ } else {
342
+ files.set(sessionId, {
343
+ record,
344
+ id,
345
+ size: bytes.length,
346
+ tail: bytes.slice(-tailLength),
347
+ })
348
+ }
349
+ return Option.some(record)
350
+ })
351
+
352
+ // Writes the whole record to a new file, then renames it over the old
353
+ // one, so a reader sees either file complete.
354
+ const writeSnapshot = Effect.fnUntraced(function* (
355
+ sessionId: string,
356
+ record: SessionRecord,
357
+ ) {
358
+ const file = fileFor(sessionId)
359
+ const temporary = `${file}.${crypto.randomUUID()}.tmp`
360
+ const id = crypto.randomUUID()
361
+ const bytes = yield* encodeLine(Snapshot.make({ record, id }))
362
+ files.delete(sessionId)
363
+ yield* fs.writeFile(temporary, bytes).pipe(
364
+ Effect.andThen(fs.rename(temporary, file)),
365
+ Effect.onError(() =>
366
+ Effect.ignore(fs.remove(temporary, { force: true })),
367
+ ),
368
+ Effect.mapError(storeError(`Failed to write session ${sessionId}`)),
369
+ )
370
+ files.set(sessionId, {
371
+ record,
372
+ id,
373
+ size: bytes.length,
374
+ tail: bytes.slice(-tailLength),
375
+ })
376
+ })
377
+
378
+ // Appends `bytes`, which may be empty, when the file is still what this layer last left
379
+ // there: the same length, ending in the same line. Another process
380
+ // only ever appends to a file, which changes its length, or replaces
381
+ // it with a snapshot, which ends in a line with a new id.
382
+ const append = Effect.fnUntraced(
383
+ function* (
384
+ sessionId: string,
385
+ known: { readonly size: number; readonly tail: Uint8Array },
386
+ bytes: Uint8Array,
387
+ ) {
388
+ const handle = yield* fs.open(fileFor(sessionId), { flag: "a+" })
389
+ const info = yield* handle.stat
390
+ if (Number(info.size) !== known.size) return false
391
+ const tail = new Uint8Array(known.tail.length)
392
+ const read = yield* handle.read(tail, {
393
+ position: BigInt(known.size - tail.length),
394
+ })
395
+ if (
396
+ read !== tail.length ||
397
+ tail.some((byte, index) => byte !== known.tail[index])
398
+ ) {
399
+ return false
400
+ }
401
+ if (bytes.length === 0) return true
402
+ // Forgotten until the append succeeds, so a failed append, which
403
+ // can leave part of a line, is followed by a snapshot.
404
+ files.delete(sessionId)
405
+ yield* handle.writeAll(bytes)
406
+ return true
407
+ },
408
+ Effect.scoped,
409
+ (effect, sessionId) =>
410
+ Effect.mapError(
411
+ effect,
412
+ storeError(`Failed to write session ${sessionId}`),
413
+ ),
414
+ )
415
+
416
+ const write = Effect.fnUntraced(function* (
417
+ sessionId: string,
418
+ record: SessionRecord,
419
+ ) {
420
+ const known = files.get(sessionId)
421
+ const changes = known && diff(known.record, record)
422
+ if (known !== undefined && changes !== undefined) {
423
+ // An unchanged record appends nothing, but is still checked
424
+ // against the file, which another process may have replaced.
425
+ if (Object.keys(changes).length === 0) {
426
+ if (yield* append(sessionId, known, new Uint8Array())) {
427
+ files.set(sessionId, { ...known, record })
428
+ return
429
+ }
430
+ } else {
431
+ const id = crypto.randomUUID()
432
+ const bytes = yield* encodeLine(
433
+ Update.make({ ...changes, parent: known.id, id }),
434
+ )
435
+ if (yield* append(sessionId, known, bytes)) {
436
+ files.set(sessionId, {
437
+ record,
438
+ id,
439
+ size: known.size + bytes.length,
440
+ tail: bytes.slice(-tailLength),
441
+ })
442
+ return
443
+ }
444
+ }
445
+ }
446
+ yield* writeSnapshot(sessionId, record)
447
+ })
448
+
449
+ return AcpSessionStore.of({
450
+ get: (sessionId) => semaphore.withPermit(read(sessionId)),
451
+ set: (sessionId, record) =>
452
+ semaphore.withPermit(write(sessionId, record)),
453
+ })
454
+ }),
455
+ )