@systemfsoftware/agent-storage-memory 0.0.0-bootstrap.0 → 0.1.0-beta.192
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.
- package/LICENSE +21 -0
- package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs +609 -0
- package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs.map +1 -0
- package/dist/MemoryMessageDeliveryStore-BmLntoBA.d.mts +18 -0
- package/dist/MemoryMessageDeliveryStore.d.mts +2 -0
- package/dist/MemoryMessageDeliveryStore.mjs +1 -0
- package/dist/MemoryScheduleStore-Bb85CXg1.mjs +163 -0
- package/dist/MemoryScheduleStore-Bb85CXg1.mjs.map +1 -0
- package/dist/MemoryScheduleStore-C_ll7Xyr.d.mts +8 -0
- package/dist/MemoryScheduleStore.d.mts +2 -0
- package/dist/MemoryScheduleStore.mjs +1 -0
- package/dist/MemorySemanticIndex-DYljUBy4.mjs +224 -0
- package/dist/MemorySemanticIndex-DYljUBy4.mjs.map +1 -0
- package/dist/MemorySemanticIndex-DrcJ7UG4.d.mts +20 -0
- package/dist/MemorySemanticIndex.d.mts +2 -0
- package/dist/MemorySemanticIndex.mjs +1 -0
- package/dist/MemorySubmissionLedger-DO-F22Gu.d.mts +28 -0
- package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs +1566 -0
- package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs.map +1 -0
- package/dist/MemorySubmissionLedger.d.mts +2 -0
- package/dist/MemorySubmissionLedger.mjs +1 -0
- package/dist/MemorySubscriptionStore-BWZ9lcIY.d.mts +7 -0
- package/dist/MemorySubscriptionStore-CFuGVxFD.mjs +929 -0
- package/dist/MemorySubscriptionStore-CFuGVxFD.mjs.map +1 -0
- package/dist/MemorySubscriptionStore.d.mts +2 -0
- package/dist/MemorySubscriptionStore.mjs +1 -0
- package/dist/MemoryThreadStore-BX3sRYhE.d.mts +21 -0
- package/dist/MemoryThreadStore-Dtwe-7h4.mjs +1415 -0
- package/dist/MemoryThreadStore-Dtwe-7h4.mjs.map +1 -0
- package/dist/MemoryThreadStore.d.mts +2 -0
- package/dist/MemoryThreadStore.mjs +1 -0
- package/dist/MemoryThreadStoreKernel-5ya9AJvL.d.mts +85 -0
- package/dist/WorkSelection-Xr9mCon_.mjs +29 -0
- package/dist/WorkSelection-Xr9mCon_.mjs.map +1 -0
- package/dist/index.d.mts +7 -0
- package/dist/index.mjs +7 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +67 -5
- package/src/MemoryMessageDeliveryStore.ts +1004 -0
- package/src/MemoryScheduleStore.ts +324 -0
- package/src/MemorySemanticIndex.ts +360 -0
- package/src/MemorySubmissionLedger.ts +3590 -0
- package/src/MemorySubscriptionStore.ts +1762 -0
- package/src/MemoryThreadStore.ts +2810 -0
- package/src/index.ts +6 -0
- package/src/internal/MemoryThreadStoreKernel.ts +156 -0
- package/src/internal/WorkSelection.ts +29 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1415 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
|
+
import { canonicalJson, utf8ByteLength } from "@systemfsoftware/agent/digest";
|
|
3
|
+
import { RunId, SubmissionId } from "@systemfsoftware/agent/identifiers";
|
|
4
|
+
import { MessageDeliveryError, prepareCanonicalMessageDeliveries } from "@systemfsoftware/agent/message-delivery";
|
|
5
|
+
import { ExportBatch, ExportRecord, ExportedRecord, ReadRecord } from "@systemfsoftware/agent/record-format";
|
|
6
|
+
import { CURRENT_RECORD_FORMAT, CanonicalRecordEnvelope, CanonicalSequence, MAX_RUN_EVIDENCE_BYTES, MAX_RUN_EVIDENCE_RECORDS, MAX_RUN_RECOVERY_SUFFIX_BYTES, MAX_RUN_RECOVERY_SUFFIX_RECORDS, MAX_RUN_TERMINAL_BYTES, ObservationOffset, PromptRecord, RUN_TERMINAL_RESERVE_RECORDS, RecordEnvelope } from "@systemfsoftware/agent/records";
|
|
7
|
+
import { ProgressAppendReader, canonicalRecordBytes, canonicalRunIds, isWorkHandoff, prepareProgressAppend, validateProgressAppend, verifyRunContinuations } from "@systemfsoftware/agent/run-continuation";
|
|
8
|
+
import { runIdForSubmission, subagentLineageRecordId, toolCallSettledRecordId, workerInputRecordId, workerOriginRecordId } from "@systemfsoftware/agent/run-journal";
|
|
9
|
+
import { StorageOwner, makeStorageOwner } from "@systemfsoftware/agent/run-storage";
|
|
10
|
+
import { submissionAbortRecordId, submissionInputRecordId, submissionSettlementRecordId } from "@systemfsoftware/agent/submission-ledger";
|
|
11
|
+
import { MAX_ARCHIVE_RANGE_BYTES, MAX_ARCHIVE_RANGE_RECORDS, ThreadArchiveRange, ThreadArchiveRangePublish, ThreadArchiveRangeRead, ThreadArchiveRangeRequest, ThreadArchiveRangeSeal } from "@systemfsoftware/agent/thread-archive-range";
|
|
12
|
+
import { ThreadDeliveryImportReader, ThreadImport, ThreadImportReader, ThreadImportRejected, captureImportSource, finishThreadImport, invalidThreadArchive, makeThreadImportProgress, prepareImportPage, rebuildClosedSubmission, validateClosedRun, verifyImportedReferences } from "@systemfsoftware/agent/thread-import";
|
|
13
|
+
import { verifyThreadInvariants } from "@systemfsoftware/agent/thread-invariants";
|
|
14
|
+
import { AppendConflict, AppendResult, PROMPT_EVIDENCE_TAGS, PreparedAppend, ThreadExportRecord, ThreadExportRejected, ThreadExportSource, ThreadIdentity, ThreadIdentityRequest, ThreadMaterialization, ThreadNotMaterialized, ThreadObservation, ThreadPeerCountRequest, ThreadPromptRead, ThreadReadRequest, ThreadReader, ThreadStore, ThreadStoreError, ThreadTail, ThreadTailRequest, ThreadVerificationRequest, ThreadWorkerCapacity, ThreadWorkerCapacityRequest, canonicalBatchFitsTransfer, streamExport, transferPageFits } from "@systemfsoftware/agent/thread-store";
|
|
15
|
+
import { ThreadExporterReader, checkExportSource, exportThreadPage } from "@systemfsoftware/agent/thread-transfer";
|
|
16
|
+
import { MAX_WORK_REBUILD_BYTES, MAX_WORK_REBUILD_RECORDS, ThreadWorkRequest, WORK_INDEX_VERSION, WorkDiscoveryUnavailable, WorkIndexRebuildRequest, WorkThreadsRequest, advanceWorkEntry, decodeWorkCursor, encodeWorkCursor, validateWorkPage, workIndexChanges } from "@systemfsoftware/agent/thread-work";
|
|
17
|
+
import * as Context from "effect/Context";
|
|
18
|
+
import * as CryptoDigest from "effect/crypto/Digest";
|
|
19
|
+
import * as Effect from "effect/Effect";
|
|
20
|
+
import * as Base64 from "effect/encoding/Base64";
|
|
21
|
+
import * as Layer from "effect/Layer";
|
|
22
|
+
import * as MutableRef from "effect/MutableRef";
|
|
23
|
+
import * as Option from "effect/Option";
|
|
24
|
+
import * as PubSub from "effect/PubSub";
|
|
25
|
+
import * as Ref from "effect/Ref";
|
|
26
|
+
import * as Schema from "effect/Schema";
|
|
27
|
+
import * as Semaphore from "effect/Semaphore";
|
|
28
|
+
import * as Stream from "effect/Stream";
|
|
29
|
+
import { n as MemoryThreadStoreKernel, t as boundedWorkSelection } from "./WorkSelection-Xr9mCon_.mjs";
|
|
30
|
+
// src/MemoryThreadStore.ts
|
|
31
|
+
var MemoryThreadStore_exports = /* @__PURE__ */ __exportAll({
|
|
32
|
+
MemoryThreadStoreLive: () => MemoryThreadStoreLive,
|
|
33
|
+
memoryThreadStoreLayer: () => memoryThreadStoreLayer
|
|
34
|
+
});
|
|
35
|
+
const MAX_THREADS = 256;
|
|
36
|
+
const RECORD_CHUNK_SIZE = 1024;
|
|
37
|
+
const READ_PAGE_SIZE = 8;
|
|
38
|
+
const ThreadCapacity = Context.Reference("@effect-agent/storage-memory/MemoryThreadStore/ThreadCapacity", { defaultValue: () => MAX_THREADS });
|
|
39
|
+
const storedRecord = (thread, sequence) => thread.chunks.get(Math.floor((sequence - 1) / RECORD_CHUNK_SIZE))?.records[(sequence - 1) % RECORD_CHUNK_SIZE];
|
|
40
|
+
const storedBytes = (thread, sequence) => thread.chunks.get(Math.floor((sequence - 1) / RECORD_CHUNK_SIZE))?.bytes[(sequence - 1) % RECORD_CHUNK_SIZE];
|
|
41
|
+
const storedPage = Effect.fnUntraced(function* (thread, after, limit) {
|
|
42
|
+
const page = [];
|
|
43
|
+
let bytes = 0;
|
|
44
|
+
for (let sequence = after + 1; sequence <= Math.min(thread.tailSequence, after + limit); sequence++) {
|
|
45
|
+
const record = storedRecord(thread, sequence);
|
|
46
|
+
if (record === void 0) return yield* storeError("read", "Incomplete canonical chunk table");
|
|
47
|
+
const size = storedBytes(thread, sequence) ?? 0;
|
|
48
|
+
if (bytes + size > 33554432) break;
|
|
49
|
+
bytes += size;
|
|
50
|
+
page.push(record);
|
|
51
|
+
}
|
|
52
|
+
return page;
|
|
53
|
+
});
|
|
54
|
+
const retainRecords = (thread, records) => {
|
|
55
|
+
for (const entry of records) {
|
|
56
|
+
const chunkId = Math.floor((entry.sequence - 1) / RECORD_CHUNK_SIZE);
|
|
57
|
+
let chunk = thread.chunks.get(chunkId);
|
|
58
|
+
if (chunk === void 0) {
|
|
59
|
+
chunk = {
|
|
60
|
+
records: [],
|
|
61
|
+
bytes: []
|
|
62
|
+
};
|
|
63
|
+
thread.chunks.set(chunkId, chunk);
|
|
64
|
+
}
|
|
65
|
+
chunk.records.push(entry);
|
|
66
|
+
chunk.bytes.push(canonicalRecordBytes(entry.record));
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const emptyIndexes = () => ({
|
|
70
|
+
toolDeclarations: /* @__PURE__ */ new Map(),
|
|
71
|
+
promptEvidence: [],
|
|
72
|
+
modelCompletions: [],
|
|
73
|
+
applicationInputs: [],
|
|
74
|
+
durableOwners: [],
|
|
75
|
+
windowBoundaries: /* @__PURE__ */ new Map(),
|
|
76
|
+
workerRecords: /* @__PURE__ */ new Map(),
|
|
77
|
+
byId: /* @__PURE__ */ new Map(),
|
|
78
|
+
runInputs: /* @__PURE__ */ new Map(),
|
|
79
|
+
runRecords: /* @__PURE__ */ new Map(),
|
|
80
|
+
handoffs: [],
|
|
81
|
+
agentUpdates: [],
|
|
82
|
+
deliveryPredecessors: [],
|
|
83
|
+
operationRecords: /* @__PURE__ */ new Map()
|
|
84
|
+
});
|
|
85
|
+
const liveInputPosition = (entries, sequence) => {
|
|
86
|
+
let low = 0;
|
|
87
|
+
let high = entries.length;
|
|
88
|
+
while (low < high) {
|
|
89
|
+
const middle = Math.floor((low + high) / 2);
|
|
90
|
+
if (entries[middle].sequence < sequence) low = middle + 1;
|
|
91
|
+
else high = middle;
|
|
92
|
+
}
|
|
93
|
+
return low;
|
|
94
|
+
};
|
|
95
|
+
const changeLiveInput = (entries, entry, change) => {
|
|
96
|
+
const at = liveInputPosition(entries, entry.createdSequence);
|
|
97
|
+
if (change === 1) entries.splice(at, 0, {
|
|
98
|
+
sequence: entry.createdSequence,
|
|
99
|
+
id: entry.id
|
|
100
|
+
});
|
|
101
|
+
else if (entries[at]?.id === entry.id) entries.splice(at, 1);
|
|
102
|
+
};
|
|
103
|
+
const emptyWorkIndex = () => ({
|
|
104
|
+
version: WORK_INDEX_VERSION,
|
|
105
|
+
state: "ready",
|
|
106
|
+
through: ZERO_CANONICAL_SEQUENCE,
|
|
107
|
+
reporting: "none",
|
|
108
|
+
entryCount: 0,
|
|
109
|
+
entries: /* @__PURE__ */ new Map(),
|
|
110
|
+
workers: /* @__PURE__ */ new Map(),
|
|
111
|
+
liveInputs: [],
|
|
112
|
+
inputsByWorker: /* @__PURE__ */ new Map()
|
|
113
|
+
});
|
|
114
|
+
const changeWorkCounts = (index, entry, change) => {
|
|
115
|
+
const owner = entry.owner;
|
|
116
|
+
if (owner._tag === "WorkerInput") {
|
|
117
|
+
changeLiveInput(index.liveInputs, entry, change);
|
|
118
|
+
let inputs = index.inputsByWorker.get(owner.workerThreadId);
|
|
119
|
+
if (inputs === void 0) index.inputsByWorker.set(owner.workerThreadId, inputs = []);
|
|
120
|
+
changeLiveInput(inputs, entry, change);
|
|
121
|
+
if (inputs.length === 0) index.inputsByWorker.delete(owner.workerThreadId);
|
|
122
|
+
let worker = index.workers.get(owner.workerThreadId);
|
|
123
|
+
if (worker === void 0) index.workers.set(owner.workerThreadId, worker = {
|
|
124
|
+
ordinary: 0,
|
|
125
|
+
update: 0,
|
|
126
|
+
effects: 0
|
|
127
|
+
});
|
|
128
|
+
if (owner.update) worker.update += change;
|
|
129
|
+
else worker.ordinary += change;
|
|
130
|
+
if (worker.ordinary + worker.update + worker.effects === 0) index.workers.delete(owner.workerThreadId);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
/** Prepare only this batch's changes; commit under the writer gate with canonical publication. */
|
|
134
|
+
const prepareWork = Effect.fnUntraced(function* (previous, records) {
|
|
135
|
+
const changes = /* @__PURE__ */ new Map();
|
|
136
|
+
let reporting = previous.reporting;
|
|
137
|
+
let through = previous.through;
|
|
138
|
+
for (const record of records) {
|
|
139
|
+
for (const change of yield* workIndexChanges(record, reporting)) if (change._tag === "WorkerMode") reporting = change.mode;
|
|
140
|
+
else if (change._tag === "Remove") {
|
|
141
|
+
const entry = changes.has(change.id) ? changes.get(change.id) : previous.entries.get(change.id);
|
|
142
|
+
if (change.stateRecordId === void 0 || entry?.stateReference._tag === "Canonical" && entry.stateReference.recordId === change.stateRecordId) changes.set(change.id, void 0);
|
|
143
|
+
} else {
|
|
144
|
+
const entry = advanceWorkEntry(changes.has(change.entry.id) ? changes.get(change.entry.id) : previous.entries.get(change.entry.id), change.entry);
|
|
145
|
+
changes.set(entry.id, entry);
|
|
146
|
+
}
|
|
147
|
+
through = record.sequence;
|
|
148
|
+
}
|
|
149
|
+
return () => {
|
|
150
|
+
const { entries } = previous;
|
|
151
|
+
for (const [id, entry] of changes) {
|
|
152
|
+
const old = entries.get(id);
|
|
153
|
+
if (old !== void 0) changeWorkCounts(previous, old, -1);
|
|
154
|
+
if (entry === void 0) entries.delete(id);
|
|
155
|
+
else {
|
|
156
|
+
entries.set(id, entry);
|
|
157
|
+
changeWorkCounts(previous, entry, 1);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
...previous,
|
|
162
|
+
through,
|
|
163
|
+
reporting,
|
|
164
|
+
entryCount: entries.size
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
});
|
|
168
|
+
/** First sequence strictly after the cursor, without traversing a Run's earlier facts. */
|
|
169
|
+
const upperSequence = (records, sequence) => {
|
|
170
|
+
let low = 0;
|
|
171
|
+
let high = records.length;
|
|
172
|
+
while (low < high) {
|
|
173
|
+
const mid = Math.floor((low + high) / 2);
|
|
174
|
+
if (records[mid].sequence <= sequence) low = mid + 1;
|
|
175
|
+
else high = mid;
|
|
176
|
+
}
|
|
177
|
+
return low;
|
|
178
|
+
};
|
|
179
|
+
const appendToIndex = (index, key, entry) => {
|
|
180
|
+
const records = index.get(key);
|
|
181
|
+
if (records === void 0) index.set(key, [entry]);
|
|
182
|
+
else records.push(entry);
|
|
183
|
+
};
|
|
184
|
+
/** Only call at successful synchronous publication, or on indexes not yet reachable by readers. */
|
|
185
|
+
const commitIndex = (index, additions) => {
|
|
186
|
+
for (const [key, entries] of additions) {
|
|
187
|
+
const records = index.get(key);
|
|
188
|
+
if (records === void 0) index.set(key, entries);
|
|
189
|
+
else for (const entry of entries) records.push(entry);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
const prepareIndexes = (previous, records) => {
|
|
193
|
+
const workerRecords = /* @__PURE__ */ new Map();
|
|
194
|
+
const wasWorker = (previous.workerRecords.get("worker") ?? []).some(({ record }) => record.payload._tag === "WorkerOriginRecorded");
|
|
195
|
+
const isWorker = wasWorker || records.some(({ record }) => record.payload._tag === "WorkerOriginRecorded");
|
|
196
|
+
if (isWorker && !wasWorker) for (const entry of previous.byId.values()) {
|
|
197
|
+
const payload = entry.record.payload;
|
|
198
|
+
if ((payload._tag === "UserInputRecorded" || payload._tag === "SubmissionSettled") && payload.runId !== void 0) {
|
|
199
|
+
const key = `execution:${payload._tag}`;
|
|
200
|
+
if ((workerRecords.get(key)?.[0]?.sequence ?? 0) < entry.sequence) workerRecords.set(key, [entry]);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const workerAppends = /* @__PURE__ */ new Map();
|
|
204
|
+
const byId = /* @__PURE__ */ new Map();
|
|
205
|
+
const runInputs = /* @__PURE__ */ new Map();
|
|
206
|
+
const runRecords = /* @__PURE__ */ new Map();
|
|
207
|
+
const handoffs = [];
|
|
208
|
+
const agentUpdates = [];
|
|
209
|
+
const deliveryPredecessors = [];
|
|
210
|
+
const nativeAdds = emptyIndexes();
|
|
211
|
+
const operationAppends = /* @__PURE__ */ new Map();
|
|
212
|
+
for (const entry of records) {
|
|
213
|
+
byId.set(entry.record.recordId, entry);
|
|
214
|
+
const payload = entry.record.payload;
|
|
215
|
+
if (payload._tag === "ModelResponseRecorded") for (const operation of payload.toolOperations) {
|
|
216
|
+
const id = toolCallSettledRecordId(payload.runId, payload.turn, operation.toolCallId);
|
|
217
|
+
nativeAdds.toolDeclarations.set(id, previous.toolDeclarations.has(id) || nativeAdds.toolDeclarations.has(id) ? null : entry);
|
|
218
|
+
}
|
|
219
|
+
if (PROMPT_EVIDENCE_TAGS.some((tag) => tag === payload._tag)) nativeAdds.promptEvidence.push(entry);
|
|
220
|
+
if (payload._tag === "ModelCompleted") nativeAdds.modelCompletions.push(entry);
|
|
221
|
+
if (payload._tag === "UserInputRecorded") {
|
|
222
|
+
const message = payload.messageAdmission;
|
|
223
|
+
if (message === void 0 || !("_tag" in message) || message._tag !== "WorkerCompletion" && message._tag !== "WorkerUpdate") nativeAdds.applicationInputs.push(entry);
|
|
224
|
+
}
|
|
225
|
+
if (payload._tag === "UserInputRecorded" && payload.submissionId !== void 0 || [
|
|
226
|
+
"RunStarted",
|
|
227
|
+
"SubmissionSettled",
|
|
228
|
+
"AbortRequested",
|
|
229
|
+
"WorkerOriginRecorded",
|
|
230
|
+
"SubagentLineageRecorded"
|
|
231
|
+
].includes(payload._tag)) nativeAdds.durableOwners.push(entry);
|
|
232
|
+
if (payload._tag === "CompactionCreated" && payload.kind === "rollover") for (let height = 0; height < 53; height++) appendToIndex(nativeAdds.windowBoundaries, `${height}:${Math.floor(payload.coversThrough / 2 ** height)}`, entry);
|
|
233
|
+
for (const runId of canonicalRunIds(entry.record)) appendToIndex(runRecords, runId, entry);
|
|
234
|
+
if (isWorkHandoff(entry.record)) handoffs.push(entry);
|
|
235
|
+
if (payload._tag === "AgentUpdateEmitted") agentUpdates.push(entry);
|
|
236
|
+
if (payload._tag === "WorkerReportPrepared" || payload._tag === "AgentUpdateEmitted" && payload.delivery !== void 0) deliveryPredecessors.push(entry);
|
|
237
|
+
if ("runId" in payload && payload.runId !== void 0 && "toolCallId" in payload) {
|
|
238
|
+
appendToIndex(operationAppends, JSON.stringify([payload.runId, payload.toolCallId]), entry);
|
|
239
|
+
if (payload._tag === "ToolApprovalRequested" || payload._tag === "ToolApprovalDecided") appendToIndex(operationAppends, JSON.stringify([
|
|
240
|
+
payload.runId,
|
|
241
|
+
payload.toolCallId,
|
|
242
|
+
"approval"
|
|
243
|
+
]), entry);
|
|
244
|
+
if (payload._tag === "ToolCallSettled") appendToIndex(operationAppends, JSON.stringify([
|
|
245
|
+
payload.runId,
|
|
246
|
+
payload.toolCallId,
|
|
247
|
+
"settled"
|
|
248
|
+
]), entry);
|
|
249
|
+
}
|
|
250
|
+
if (isWorker && (payload._tag === "UserInputRecorded" || payload._tag === "SubmissionSettled") && payload.runId !== void 0) workerRecords.set(`execution:${payload._tag}`, [entry]);
|
|
251
|
+
const workerKey = payload._tag === "SubtreeBudgetReserved" ? `subtree:${payload.sourceSubmissionId ?? ""}` : payload._tag === "SubagentJoined" ? `joined:${payload.runId}` : [
|
|
252
|
+
"ThreadCreated",
|
|
253
|
+
"WorkerOriginRecorded",
|
|
254
|
+
"SubagentLineageRecorded"
|
|
255
|
+
].includes(payload._tag) ? "worker" : void 0;
|
|
256
|
+
if (workerKey !== void 0) appendToIndex(workerAppends, workerKey, entry);
|
|
257
|
+
if (payload._tag === "WorkerStopRequested") appendToIndex(workerAppends, `stop:${payload.command.worker.threadId}`, entry);
|
|
258
|
+
if (payload._tag === "WorkerInputRequested" && payload.admission.sourceSubmissionId !== void 0) appendToIndex(workerAppends, `funding:${payload.admission.sourceSubmissionId}`, entry);
|
|
259
|
+
if (payload._tag === "WorkerInputCompleted") {
|
|
260
|
+
const admission = (previous.byId.get(workerInputRecordId(payload.messageId)) ?? byId.get(workerInputRecordId(payload.messageId)))?.record.payload;
|
|
261
|
+
if (admission?._tag === "WorkerInputRequested" && admission.admission.sourceSubmissionId !== void 0) appendToIndex(workerAppends, `funding:${admission.admission.sourceSubmissionId}`, entry);
|
|
262
|
+
}
|
|
263
|
+
if (payload._tag === "WorkerInputRefused") {
|
|
264
|
+
const reserved = (previous.byId.get(payload.reservation.recordId) ?? byId.get(payload.reservation.recordId))?.record.payload;
|
|
265
|
+
const sourceSubmissionId = reserved?._tag === "WorkerInputRequested" ? reserved.admission.sourceSubmissionId : reserved?._tag === "SubtreeBudgetReserved" ? reserved.sourceSubmissionId : void 0;
|
|
266
|
+
if (sourceSubmissionId !== void 0) appendToIndex(workerAppends, `funding:${sourceSubmissionId}`, entry);
|
|
267
|
+
}
|
|
268
|
+
if (payload._tag === "UserInputRecorded" && payload.kind === "user" && payload.runId !== void 0) runInputs.set(payload.runId, runInputs.has(payload.runId) || previous.runInputs.has(payload.runId) ? null : entry);
|
|
269
|
+
}
|
|
270
|
+
return {
|
|
271
|
+
indexes: previous,
|
|
272
|
+
commit: () => {
|
|
273
|
+
commitIndex(previous.runRecords, runRecords);
|
|
274
|
+
commitIndex(previous.operationRecords, operationAppends);
|
|
275
|
+
for (const [id, entry] of nativeAdds.toolDeclarations) previous.toolDeclarations.set(id, entry);
|
|
276
|
+
for (const key of [
|
|
277
|
+
"promptEvidence",
|
|
278
|
+
"modelCompletions",
|
|
279
|
+
"applicationInputs"
|
|
280
|
+
]) for (const entry of nativeAdds[key]) previous[key].push(entry);
|
|
281
|
+
commitIndex(previous.windowBoundaries, nativeAdds.windowBoundaries);
|
|
282
|
+
if (previous.durableOwners.length === 0 && nativeAdds.durableOwners[0] !== void 0) previous.durableOwners.push(nativeAdds.durableOwners[0]);
|
|
283
|
+
for (const [id, entry] of byId) previous.byId.set(id, entry);
|
|
284
|
+
for (const [id, entry] of runInputs) previous.runInputs.set(id, entry);
|
|
285
|
+
for (const [key, entries] of workerRecords) previous.workerRecords.set(key, entries);
|
|
286
|
+
commitIndex(previous.workerRecords, workerAppends);
|
|
287
|
+
for (const entry of handoffs) previous.handoffs.push(entry);
|
|
288
|
+
for (const entry of agentUpdates) previous.agentUpdates.push(entry);
|
|
289
|
+
for (const entry of deliveryPredecessors) previous.deliveryPredecessors.push(entry);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
const storeError = (operation, message, cause) => cause === void 0 ? ThreadStoreError.make({
|
|
294
|
+
operation,
|
|
295
|
+
message
|
|
296
|
+
}) : ThreadStoreError.make({
|
|
297
|
+
operation,
|
|
298
|
+
message,
|
|
299
|
+
cause
|
|
300
|
+
});
|
|
301
|
+
const deliveryError = (message, cause) => ThreadStoreError.make({
|
|
302
|
+
operation: "append",
|
|
303
|
+
message,
|
|
304
|
+
cause,
|
|
305
|
+
deliveryReason: cause.reason
|
|
306
|
+
});
|
|
307
|
+
const validate = (schema, operation, value) => Schema.encodeUnknownEffect(schema)(value).pipe(Effect.flatMap(Schema.decodeUnknownEffect(schema)), Effect.mapError((error) => storeError(operation, `Invalid ${operation} request`, error)));
|
|
308
|
+
const decodeCanonicalSequence = Schema.decodeSync(CanonicalSequence);
|
|
309
|
+
const ZERO_CANONICAL_SEQUENCE = decodeCanonicalSequence(0);
|
|
310
|
+
const offsetSequence = Effect.fnUntraced(function* (threadId, offset) {
|
|
311
|
+
if (offset === void 0) return yield* Effect.succeed(ZERO_CANONICAL_SEQUENCE);
|
|
312
|
+
const prefix = `memory:v1:${Base64.encode(threadId)}:`;
|
|
313
|
+
const encodedSequence = offset.startsWith(prefix) ? offset.slice(prefix.length) : "";
|
|
314
|
+
if (!/^\d+$/.test(encodedSequence)) return yield* storeError("observe", "Malformed observation offset");
|
|
315
|
+
const sequence = Number(encodedSequence);
|
|
316
|
+
return yield* Number.isSafeInteger(sequence) ? Schema.decodeEffect(CanonicalSequence)(sequence).pipe(Effect.mapError(() => storeError("observe", "Malformed observation offset"))) : Effect.fail(storeError("observe", "Malformed observation offset"));
|
|
317
|
+
});
|
|
318
|
+
const observationOffset = (threadId, sequence) => Schema.decodeSync(ObservationOffset)(`memory:v1:${Base64.encode(threadId)}:${sequence}`);
|
|
319
|
+
const batchEnvelopes = (threadId, batch, firstSequence) => batch.records.map((record, index) => {
|
|
320
|
+
const sequence = decodeCanonicalSequence(firstSequence + index);
|
|
321
|
+
return CanonicalRecordEnvelope.make({
|
|
322
|
+
threadId,
|
|
323
|
+
batchId: batch.batchId,
|
|
324
|
+
sequence,
|
|
325
|
+
offset: observationOffset(threadId, sequence),
|
|
326
|
+
record
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
const decodeStoredBatch = (batchJson, operation) => Schema.decodeEffect(Schema.fromJsonString(ExportBatch))(batchJson).pipe(Effect.mapError((cause) => storeError(operation, "Invalid canonical batch JSON", cause)));
|
|
330
|
+
const findThread = Effect.fnUntraced(function* (state, threadId) {
|
|
331
|
+
const thread = state.threads.get(threadId);
|
|
332
|
+
return yield* thread === void 0 ? Effect.fail(ThreadNotMaterialized.make({ threadId })) : Effect.succeed(thread);
|
|
333
|
+
});
|
|
334
|
+
const makeThreadStore = Effect.gen(function* () {
|
|
335
|
+
const maxThreads = yield* ThreadCapacity;
|
|
336
|
+
const crypto = yield* CryptoDigest.Digest;
|
|
337
|
+
const state = yield* Ref.make({ threads: /* @__PURE__ */ new Map() });
|
|
338
|
+
const gate = yield* Semaphore.make(1);
|
|
339
|
+
const owner = yield* makeStorageOwner(gate.withPermits(1));
|
|
340
|
+
const withMutation = owner.withMutation;
|
|
341
|
+
const updates = yield* PubSub.sliding(1);
|
|
342
|
+
let ledgerTransfer;
|
|
343
|
+
let deliveryTransfer;
|
|
344
|
+
let deliveryWriter;
|
|
345
|
+
const workState = yield* Ref.make(/* @__PURE__ */ new Map());
|
|
346
|
+
const workOwners = /* @__PURE__ */ new Map();
|
|
347
|
+
const publishWork = (threadId, index) => MutableRef.get(workState.ref).set(threadId, index);
|
|
348
|
+
const readyIndex = (threadId, tail) => {
|
|
349
|
+
const index = MutableRef.get(workState.ref).get(threadId);
|
|
350
|
+
if (index === void 0 || index.version !== WORK_INDEX_VERSION || index.entries.size !== index.entryCount) return Effect.fail(WorkDiscoveryUnavailable.make({
|
|
351
|
+
threadId,
|
|
352
|
+
reason: "missing-index"
|
|
353
|
+
}));
|
|
354
|
+
if (index.state !== "ready" || index.through !== tail) return Effect.fail(WorkDiscoveryUnavailable.make({
|
|
355
|
+
threadId,
|
|
356
|
+
reason: "incomplete-rebuild"
|
|
357
|
+
}));
|
|
358
|
+
return Effect.succeed(index);
|
|
359
|
+
};
|
|
360
|
+
const work = {
|
|
361
|
+
threads: (unvalidated) => withMutation(Effect.gen(function* () {
|
|
362
|
+
const request = yield* validate(WorkThreadsRequest, "work threads", unvalidated);
|
|
363
|
+
const current = yield* Ref.get(state);
|
|
364
|
+
const catalogue = yield* Ref.get(workState);
|
|
365
|
+
const candidates = boundedWorkSelection(request.limit, (id) => id, request.afterThreadId);
|
|
366
|
+
for (const [threadId, thread] of current.threads) {
|
|
367
|
+
const index = catalogue.get(threadId);
|
|
368
|
+
if (index === void 0 || index.version !== WORK_INDEX_VERSION || index.state !== "ready" || index.through !== thread.tailSequence || index.entryCount !== index.entries.size || index.entryCount > 0) candidates.add(threadId);
|
|
369
|
+
}
|
|
370
|
+
for (const owner of workOwners.values()) {
|
|
371
|
+
const page = yield* owner.threads(request);
|
|
372
|
+
for (const threadId of page.threadIds) candidates.add(threadId);
|
|
373
|
+
}
|
|
374
|
+
const threadIds = candidates.values;
|
|
375
|
+
const afterThreadId = threadIds.length === request.limit ? threadIds.at(-1) : void 0;
|
|
376
|
+
return {
|
|
377
|
+
threadIds,
|
|
378
|
+
...afterThreadId === void 0 ? {} : { afterThreadId }
|
|
379
|
+
};
|
|
380
|
+
})),
|
|
381
|
+
page: (unvalidated) => withMutation(Effect.gen(function* () {
|
|
382
|
+
const request = yield* validate(ThreadWorkRequest, "work page", unvalidated);
|
|
383
|
+
const cursor = yield* decodeWorkCursor(request).pipe(Effect.provideService(CryptoDigest.Digest, crypto));
|
|
384
|
+
const thread = (yield* Ref.get(state)).threads.get(request.threadId);
|
|
385
|
+
const index = yield* readyIndex(request.threadId, thread?.tailSequence ?? 0);
|
|
386
|
+
if (cursor.source === "canonical") {
|
|
387
|
+
const candidates = boundedWorkSelection(request.limit + 1, (entry) => entry.id, cursor.after);
|
|
388
|
+
for (const entry of index.entries.values()) candidates.add(entry);
|
|
389
|
+
const selected = candidates.values;
|
|
390
|
+
const entries = selected.slice(0, request.limit);
|
|
391
|
+
const after = selected.length > request.limit ? entries.at(-1)?.id : void 0;
|
|
392
|
+
return yield* validateWorkPage({
|
|
393
|
+
entries,
|
|
394
|
+
cursor: encodeWorkCursor({
|
|
395
|
+
version: WORK_INDEX_VERSION,
|
|
396
|
+
threadDigest: cursor.threadDigest,
|
|
397
|
+
source: after === void 0 ? "deliveries" : "canonical",
|
|
398
|
+
...after === void 0 ? {} : { after }
|
|
399
|
+
})
|
|
400
|
+
}, request.limit);
|
|
401
|
+
}
|
|
402
|
+
const page = yield* workOwners.get(cursor.source)?.page(request.threadId, cursor.after, request.limit) ?? Effect.succeed({ entries: [] });
|
|
403
|
+
const next = page.after === void 0 ? cursor.source === "admissions" ? "canonical" : void 0 : cursor.source;
|
|
404
|
+
return yield* validateWorkPage({
|
|
405
|
+
entries: [...page.entries],
|
|
406
|
+
...next === void 0 ? {} : { cursor: encodeWorkCursor({
|
|
407
|
+
version: WORK_INDEX_VERSION,
|
|
408
|
+
threadDigest: cursor.threadDigest,
|
|
409
|
+
source: next,
|
|
410
|
+
...page.after === void 0 ? {} : { after: page.after }
|
|
411
|
+
}) }
|
|
412
|
+
}, request.limit);
|
|
413
|
+
})),
|
|
414
|
+
rebuild: (unvalidated) => withMutation(Effect.gen(function* () {
|
|
415
|
+
const request = yield* validate(WorkIndexRebuildRequest, "rebuild work", unvalidated);
|
|
416
|
+
const current = yield* Ref.get(state);
|
|
417
|
+
const thread = current.threads.get(request.threadId);
|
|
418
|
+
const tail = thread?.tailSequence ?? ZERO_CANONICAL_SEQUENCE;
|
|
419
|
+
const prior = (yield* Ref.get(workState)).get(request.threadId);
|
|
420
|
+
const index = request.restart || prior === void 0 || prior.version !== WORK_INDEX_VERSION || prior.entries.size !== prior.entryCount || prior.state === "ready" && prior.through !== tail ? {
|
|
421
|
+
...emptyWorkIndex(),
|
|
422
|
+
state: "rebuilding",
|
|
423
|
+
rebuildingIndexes: emptyIndexes()
|
|
424
|
+
} : prior;
|
|
425
|
+
if (index.state === "ready") return {
|
|
426
|
+
version: WORK_INDEX_VERSION,
|
|
427
|
+
threadId: request.threadId,
|
|
428
|
+
state: "ready",
|
|
429
|
+
throughSequence: index.through,
|
|
430
|
+
tailSequence: tail,
|
|
431
|
+
processedRecords: 0,
|
|
432
|
+
processedBytes: 0
|
|
433
|
+
};
|
|
434
|
+
if (index.rebuildingIndexes === void 0) return yield* WorkDiscoveryUnavailable.make({
|
|
435
|
+
threadId: request.threadId,
|
|
436
|
+
reason: "incomplete-rebuild"
|
|
437
|
+
});
|
|
438
|
+
const rebuildingIndexes = index.rebuildingIndexes;
|
|
439
|
+
const records = [];
|
|
440
|
+
let bytes = 0;
|
|
441
|
+
const end = Math.min(tail, index.through + (request.limit ?? MAX_WORK_REBUILD_RECORDS));
|
|
442
|
+
for (let position = index.through; position < end; position++) {
|
|
443
|
+
const size = thread === void 0 ? void 0 : storedBytes(thread, position + 1);
|
|
444
|
+
if (size === void 0) return yield* storeError("rebuild work", "Canonical record byte length is missing");
|
|
445
|
+
if (bytes + size > MAX_WORK_REBUILD_BYTES) break;
|
|
446
|
+
const record = thread === void 0 ? void 0 : storedRecord(thread, position + 1);
|
|
447
|
+
if (record === void 0 || record.sequence !== position + 1) return yield* storeError("rebuild work", "Canonical rebuild sequence is incomplete");
|
|
448
|
+
bytes += size;
|
|
449
|
+
records.push(record);
|
|
450
|
+
}
|
|
451
|
+
if (index.through < tail && records.length === 0) return yield* storeError("rebuild work", "Canonical rebuild cannot advance within its byte bound");
|
|
452
|
+
const commitWork = yield* prepareWork(index, records).pipe(Effect.provideService(CryptoDigest.Digest, crypto));
|
|
453
|
+
const next = yield* Effect.sync(() => {
|
|
454
|
+
const native = prepareIndexes(rebuildingIndexes, records);
|
|
455
|
+
const rebuilt = commitWork();
|
|
456
|
+
const complete = rebuilt.through === tail;
|
|
457
|
+
const next = {
|
|
458
|
+
version: rebuilt.version,
|
|
459
|
+
through: rebuilt.through,
|
|
460
|
+
reporting: rebuilt.reporting,
|
|
461
|
+
entryCount: rebuilt.entryCount,
|
|
462
|
+
entries: rebuilt.entries,
|
|
463
|
+
workers: rebuilt.workers,
|
|
464
|
+
liveInputs: rebuilt.liveInputs,
|
|
465
|
+
inputsByWorker: rebuilt.inputsByWorker,
|
|
466
|
+
state: complete ? "ready" : "rebuilding",
|
|
467
|
+
...complete ? {} : { rebuildingIndexes: native.indexes }
|
|
468
|
+
};
|
|
469
|
+
native.commit();
|
|
470
|
+
if (thread !== void 0 && complete) MutableRef.set(state.ref, { threads: new Map(current.threads).set(request.threadId, {
|
|
471
|
+
...thread,
|
|
472
|
+
...native.indexes
|
|
473
|
+
}) });
|
|
474
|
+
publishWork(request.threadId, next);
|
|
475
|
+
return next;
|
|
476
|
+
});
|
|
477
|
+
return {
|
|
478
|
+
version: WORK_INDEX_VERSION,
|
|
479
|
+
threadId: request.threadId,
|
|
480
|
+
state: next.state,
|
|
481
|
+
throughSequence: next.through,
|
|
482
|
+
tailSequence: tail,
|
|
483
|
+
processedRecords: records.length,
|
|
484
|
+
processedBytes: bytes
|
|
485
|
+
};
|
|
486
|
+
}))
|
|
487
|
+
};
|
|
488
|
+
yield* Effect.addFinalizer(() => PubSub.shutdown(updates));
|
|
489
|
+
const materialize = Effect.fnUntraced(function* (unvalidated) {
|
|
490
|
+
const request = yield* validate(ThreadMaterialization, "materialize", unvalidated);
|
|
491
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
492
|
+
if (current.threads.get(request.threadId) !== void 0) return [{ _tag: "success" }, current];
|
|
493
|
+
if (!MutableRef.get(workState.ref).has(request.threadId) && MutableRef.get(workState.ref).size >= maxThreads) return [{
|
|
494
|
+
_tag: "failure",
|
|
495
|
+
error: storeError("materialize", `In-memory thread limit ${maxThreads} exceeded`)
|
|
496
|
+
}, current];
|
|
497
|
+
if (!transferPageFits(request.threadId)) return [{
|
|
498
|
+
_tag: "failure",
|
|
499
|
+
error: storeError("materialize", "Thread identity exceeds its bounded transfer representation")
|
|
500
|
+
}, current];
|
|
501
|
+
const threads = new Map(current.threads);
|
|
502
|
+
threads.set(request.threadId, {
|
|
503
|
+
tailSequence: ZERO_CANONICAL_SEQUENCE,
|
|
504
|
+
byId: /* @__PURE__ */ new Map(),
|
|
505
|
+
workerRecords: /* @__PURE__ */ new Map(),
|
|
506
|
+
runInputs: /* @__PURE__ */ new Map(),
|
|
507
|
+
runRecords: /* @__PURE__ */ new Map(),
|
|
508
|
+
operationRecords: /* @__PURE__ */ new Map(),
|
|
509
|
+
handoffs: [],
|
|
510
|
+
agentUpdates: [],
|
|
511
|
+
deliveryPredecessors: [],
|
|
512
|
+
toolDeclarations: /* @__PURE__ */ new Map(),
|
|
513
|
+
promptEvidence: [],
|
|
514
|
+
modelCompletions: [],
|
|
515
|
+
applicationInputs: [],
|
|
516
|
+
durableOwners: [],
|
|
517
|
+
windowBoundaries: /* @__PURE__ */ new Map(),
|
|
518
|
+
ranges: /* @__PURE__ */ new Map(),
|
|
519
|
+
rangeStarts: [],
|
|
520
|
+
archiveContents: /* @__PURE__ */ new Map(),
|
|
521
|
+
chunks: /* @__PURE__ */ new Map(),
|
|
522
|
+
batchesByFirst: /* @__PURE__ */ new Map(),
|
|
523
|
+
batches: /* @__PURE__ */ new Map(),
|
|
524
|
+
executions: /* @__PURE__ */ new Map(),
|
|
525
|
+
executionCommits: /* @__PURE__ */ new Map()
|
|
526
|
+
});
|
|
527
|
+
publishWork(request.threadId, emptyWorkIndex());
|
|
528
|
+
return [{ _tag: "success" }, { threads }];
|
|
529
|
+
});
|
|
530
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
531
|
+
});
|
|
532
|
+
const prepareAppend = Effect.fnUntraced(function* (unvalidated) {
|
|
533
|
+
const captured = yield* PreparedAppend.capture(unvalidated);
|
|
534
|
+
const request = captured;
|
|
535
|
+
const batchJson = captured.batchJson;
|
|
536
|
+
const batchBytes = new TextEncoder().encode(batchJson).byteLength;
|
|
537
|
+
if (batchBytes > 16777216) return yield* storeError("append", "Canonical batch exceeds 16 MiB");
|
|
538
|
+
const offsetBytes = 4 * Math.ceil(utf8ByteLength(request.threadId) / 3) + 36;
|
|
539
|
+
if (!canonicalBatchFitsTransfer(request.threadId, request.batch, batchBytes, offsetBytes)) return yield* storeError("append", "Canonical batch exceeds its bounded transfer representation");
|
|
540
|
+
return {
|
|
541
|
+
request,
|
|
542
|
+
batchJson,
|
|
543
|
+
deliveries: yield* prepareCanonicalMessageDeliveries(request.threadId, request.batch.records).pipe(Effect.provideService(CryptoDigest.Digest, crypto), Effect.mapError((cause) => deliveryError("Invalid canonical delivery", cause)))
|
|
544
|
+
};
|
|
545
|
+
});
|
|
546
|
+
const appendPrepared = Effect.fnUntraced(function* ({ request, batchJson, deliveries }) {
|
|
547
|
+
const thread = (yield* Ref.get(state)).threads.get(request.threadId);
|
|
548
|
+
const executionIntent = JSON.stringify({
|
|
549
|
+
batch: batchJson,
|
|
550
|
+
operational: (request.executions ?? []).flatMap((update) => update.facts.map((fact) => Schema.encodeSync(RecordEnvelope)(fact)))
|
|
551
|
+
});
|
|
552
|
+
const latestIntent = thread === void 0 ? void 0 : [...thread.executionCommits.values()].find((entry) => entry.batchId === request.batch.batchId);
|
|
553
|
+
if (thread !== void 0 && latestIntent === void 0 && request.batch.records.length === 0) for (const update of request.executions ?? []) {
|
|
554
|
+
const prior = thread.executions.get(update.checkpoint.progress.runId);
|
|
555
|
+
if (prior !== void 0 && update.previousRevision < prior.progress.revision && update.facts.every((fact) => prior.operational.some((known) => known.recordId === fact.recordId))) return yield* AppendConflict.make({
|
|
556
|
+
threadId: request.threadId,
|
|
557
|
+
batchId: request.batch.batchId,
|
|
558
|
+
reason: "stale-command"
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
if (thread !== void 0 && thread.tailSequence === request.expectedTailSequence && !thread.batches.has(request.batch.batchId) && latestIntent === void 0) {
|
|
562
|
+
const executions = request.executions ?? [];
|
|
563
|
+
if (new Set(executions.map((update) => update.checkpoint.progress.runId)).size !== executions.length) return yield* storeError("append", "Duplicate active execution identity");
|
|
564
|
+
for (const update of request.executions ?? []) {
|
|
565
|
+
const prior = thread.executions.get(update.checkpoint.progress.runId);
|
|
566
|
+
if ((prior?.progress.revision ?? 0) !== update.previousRevision) return yield* AppendConflict.make({
|
|
567
|
+
threadId: request.threadId,
|
|
568
|
+
batchId: request.batch.batchId,
|
|
569
|
+
reason: "tail",
|
|
570
|
+
actualTailSequence: thread.tailSequence
|
|
571
|
+
});
|
|
572
|
+
if (update.checkpoint.throughSequence !== thread.tailSequence + request.batch.records.length || update.checkpoint.batchId !== request.batch.batchId || prior !== void 0 && update.checkpoint.originalSequence !== prior.originalSequence) return yield* storeError("append", "Active checkpoint differs from its committed history boundary");
|
|
573
|
+
if (update.retire && ![...request.batch.records, ...(thread.runRecords.get(update.checkpoint.progress.runId) ?? []).map((entry) => entry.record)].some(({ payload }) => payload._tag === "SubmissionSettled" && payload.runId === update.checkpoint.progress.runId && payload.submissionId === update.checkpoint.progress.submissionId)) return yield* storeError("append", "Active state cannot retire without a canonical terminal outcome");
|
|
574
|
+
}
|
|
575
|
+
yield* validateProgressAppend(prepareProgressAppend(request.batch.records), request.executions).pipe(Effect.provideService(ProgressAppendReader, {
|
|
576
|
+
previous: (runId) => Effect.succeed(thread.executions.get(runId)?.progress),
|
|
577
|
+
initial: (next) => Effect.succeed((thread.runRecords.get(next.runId) ?? []).map((entry) => entry.record))
|
|
578
|
+
}));
|
|
579
|
+
}
|
|
580
|
+
const currentWork = (yield* Ref.get(workState)).get(request.threadId);
|
|
581
|
+
const preparedWork = thread !== void 0 && thread.tailSequence === request.expectedTailSequence && !thread.batches.has(request.batch.batchId) && latestIntent === void 0 && currentWork?.version === WORK_INDEX_VERSION && currentWork.state === "ready" && currentWork.through === thread.tailSequence && currentWork.entryCount === currentWork.entries.size ? yield* prepareWork(currentWork, batchEnvelopes(request.threadId, request.batch, decodeCanonicalSequence(thread.tailSequence + 1))).pipe(Effect.provideService(CryptoDigest.Digest, crypto)) : void 0;
|
|
582
|
+
let commitDeliveries;
|
|
583
|
+
if (deliveries.length > 0) {
|
|
584
|
+
if (deliveryWriter === void 0) return yield* deliveryError("Canonical messages require a paired MemoryMessageDeliveryStore", MessageDeliveryError.make({
|
|
585
|
+
reason: "storage",
|
|
586
|
+
operation: "canonical publication"
|
|
587
|
+
}));
|
|
588
|
+
commitDeliveries = yield* deliveryWriter(deliveries).pipe(Effect.mapError((cause) => deliveryError("Canonical delivery rejected", cause)));
|
|
589
|
+
}
|
|
590
|
+
const decision = yield* Effect.uninterruptible(Ref.modify(state, (current) => {
|
|
591
|
+
const thread = current.threads.get(request.threadId);
|
|
592
|
+
if (thread === void 0) return [{
|
|
593
|
+
_tag: "failure",
|
|
594
|
+
error: ThreadNotMaterialized.make({ threadId: request.threadId })
|
|
595
|
+
}, current];
|
|
596
|
+
const priorExecution = latestIntent;
|
|
597
|
+
if (priorExecution !== void 0) {
|
|
598
|
+
if (priorExecution.intent !== executionIntent) return [{
|
|
599
|
+
_tag: "failure",
|
|
600
|
+
error: AppendConflict.make({
|
|
601
|
+
threadId: request.threadId,
|
|
602
|
+
batchId: request.batch.batchId,
|
|
603
|
+
reason: "batch-content"
|
|
604
|
+
})
|
|
605
|
+
}, current];
|
|
606
|
+
commitDeliveries?.();
|
|
607
|
+
return [{
|
|
608
|
+
_tag: "success",
|
|
609
|
+
result: AppendResult.make({
|
|
610
|
+
...priorExecution.result,
|
|
611
|
+
replayed: true
|
|
612
|
+
}),
|
|
613
|
+
records: []
|
|
614
|
+
}, current];
|
|
615
|
+
}
|
|
616
|
+
const previous = thread.batches.get(request.batch.batchId);
|
|
617
|
+
if (previous !== void 0) {
|
|
618
|
+
if (previous.batchJson !== batchJson) return [{
|
|
619
|
+
_tag: "failure",
|
|
620
|
+
error: AppendConflict.make({
|
|
621
|
+
threadId: request.threadId,
|
|
622
|
+
batchId: request.batch.batchId,
|
|
623
|
+
reason: "batch-content"
|
|
624
|
+
})
|
|
625
|
+
}, current];
|
|
626
|
+
commitDeliveries?.();
|
|
627
|
+
return [{
|
|
628
|
+
_tag: "success",
|
|
629
|
+
result: AppendResult.make({
|
|
630
|
+
firstSequence: previous.result.firstSequence,
|
|
631
|
+
lastSequence: previous.result.lastSequence,
|
|
632
|
+
replayed: true
|
|
633
|
+
}),
|
|
634
|
+
records: []
|
|
635
|
+
}, current];
|
|
636
|
+
}
|
|
637
|
+
if (request.expectedTailSequence !== thread.tailSequence) return [{
|
|
638
|
+
_tag: "failure",
|
|
639
|
+
error: AppendConflict.make({
|
|
640
|
+
threadId: request.threadId,
|
|
641
|
+
batchId: request.batch.batchId,
|
|
642
|
+
reason: "tail",
|
|
643
|
+
actualTailSequence: thread.tailSequence
|
|
644
|
+
})
|
|
645
|
+
}, current];
|
|
646
|
+
const batchRecordIds = /* @__PURE__ */ new Set();
|
|
647
|
+
for (const record of request.batch.records) {
|
|
648
|
+
if (thread.byId.has(record.recordId) || batchRecordIds.has(record.recordId)) return [{
|
|
649
|
+
_tag: "failure",
|
|
650
|
+
error: AppendConflict.make({
|
|
651
|
+
threadId: request.threadId,
|
|
652
|
+
batchId: request.batch.batchId,
|
|
653
|
+
reason: "record-identity"
|
|
654
|
+
})
|
|
655
|
+
}, current];
|
|
656
|
+
batchRecordIds.add(record.recordId);
|
|
657
|
+
}
|
|
658
|
+
const records = batchEnvelopes(request.threadId, request.batch, decodeCanonicalSequence(thread.tailSequence + 1));
|
|
659
|
+
const lastSequence = decodeCanonicalSequence(thread.tailSequence + records.length);
|
|
660
|
+
const result = AppendResult.make({
|
|
661
|
+
firstSequence: decodeCanonicalSequence(thread.tailSequence + (records.length > 0 ? 1 : 0)),
|
|
662
|
+
lastSequence,
|
|
663
|
+
replayed: false
|
|
664
|
+
});
|
|
665
|
+
const indexes = prepareIndexes(thread, records);
|
|
666
|
+
const next = {
|
|
667
|
+
...thread,
|
|
668
|
+
...indexes.indexes,
|
|
669
|
+
tailSequence: lastSequence
|
|
670
|
+
};
|
|
671
|
+
if (records.length > 0) {
|
|
672
|
+
thread.batches.set(request.batch.batchId, {
|
|
673
|
+
result,
|
|
674
|
+
batchJson
|
|
675
|
+
});
|
|
676
|
+
thread.batchesByFirst.set(result.firstSequence, request.batch.batchId);
|
|
677
|
+
retainRecords(thread, records);
|
|
678
|
+
}
|
|
679
|
+
for (const update of request.executions ?? []) {
|
|
680
|
+
const runId = update.checkpoint.progress.runId;
|
|
681
|
+
if (update.retire) {
|
|
682
|
+
thread.executions.delete(runId);
|
|
683
|
+
thread.executionCommits.delete(runId);
|
|
684
|
+
} else {
|
|
685
|
+
thread.executions.set(runId, update.checkpoint);
|
|
686
|
+
thread.executionCommits.set(runId, {
|
|
687
|
+
batchId: request.batch.batchId,
|
|
688
|
+
intent: executionIntent,
|
|
689
|
+
result
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
indexes.commit();
|
|
694
|
+
if (preparedWork !== void 0) publishWork(request.threadId, preparedWork());
|
|
695
|
+
current.threads.set(request.threadId, next);
|
|
696
|
+
commitDeliveries?.();
|
|
697
|
+
return [{
|
|
698
|
+
_tag: "success",
|
|
699
|
+
result,
|
|
700
|
+
records
|
|
701
|
+
}, current];
|
|
702
|
+
}).pipe(Effect.tap((decision) => decision._tag === "success" && decision.records.length > 0 ? PubSub.publish(updates, void 0) : Effect.void)));
|
|
703
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
704
|
+
return decision.result;
|
|
705
|
+
});
|
|
706
|
+
const append = Effect.fn("MemoryThreadStore.append")((request) => prepareAppend(request).pipe(Effect.flatMap((prepared) => owner.withProgress(prepared.request.threadId, withMutation(appendPrepared(prepared))))));
|
|
707
|
+
const countPeerMessages = Effect.fnUntraced(function* (request) {
|
|
708
|
+
yield* validate(ThreadPeerCountRequest, "countPeerMessages", request);
|
|
709
|
+
yield* findThread(yield* Ref.get(state), request.threadId);
|
|
710
|
+
return Math.min(deliveryTransfer?.peerCount(request.threadId, request.nowMillis, request.limit) ?? 0, request.limit);
|
|
711
|
+
});
|
|
712
|
+
const readSnapshot = (threadId, afterSequence, limit) => Ref.get(state).pipe(Effect.flatMap((current) => findThread(current, threadId)), Effect.flatMap((thread) => {
|
|
713
|
+
return storedPage(thread, afterSequence ?? ZERO_CANONICAL_SEQUENCE, limit);
|
|
714
|
+
}));
|
|
715
|
+
const selectedStream = (sources, after, through, maximum) => Stream.paginate({
|
|
716
|
+
after,
|
|
717
|
+
count: 0
|
|
718
|
+
}, (cursor) => Effect.gen(function* () {
|
|
719
|
+
const page = [];
|
|
720
|
+
let bytes = 0;
|
|
721
|
+
let last = cursor.after;
|
|
722
|
+
while (page.length < Math.min(READ_PAGE_SIZE, maximum - cursor.count)) {
|
|
723
|
+
let selected;
|
|
724
|
+
for (const source of sources) {
|
|
725
|
+
const next = source[upperSequence(source, last)];
|
|
726
|
+
if (next !== void 0 && next.sequence <= through && (selected === void 0 || next.sequence < selected.sequence)) selected = next;
|
|
727
|
+
}
|
|
728
|
+
if (selected === void 0) break;
|
|
729
|
+
const size = canonicalRecordBytes(selected.record);
|
|
730
|
+
if (size > 33554432) return yield* storeError("read", "Canonical value exceeds the page byte bound");
|
|
731
|
+
if (bytes + size > 33554432) break;
|
|
732
|
+
bytes += size;
|
|
733
|
+
page.push(selected);
|
|
734
|
+
last = selected.sequence;
|
|
735
|
+
}
|
|
736
|
+
const next = {
|
|
737
|
+
after: last,
|
|
738
|
+
count: cursor.count + page.length
|
|
739
|
+
};
|
|
740
|
+
return [page, page.length === 0 || next.count >= maximum ? Option.none() : Option.some(next)];
|
|
741
|
+
}));
|
|
742
|
+
const readFromThread = (threadId, thread, request) => Stream.unwrap(Effect.gen(function* () {
|
|
743
|
+
if (request.threadId !== threadId) return yield* storeError("read snapshot", "Thread differs from the captured snapshot");
|
|
744
|
+
if (!("selection" in request)) return Stream.paginate({
|
|
745
|
+
after: request.afterSequence ?? ZERO_CANONICAL_SEQUENCE,
|
|
746
|
+
count: 0
|
|
747
|
+
}, (cursor) => Effect.gen(function* () {
|
|
748
|
+
const page = yield* storedPage(thread, cursor.after, Math.min(READ_PAGE_SIZE, request.limit - cursor.count));
|
|
749
|
+
const next = {
|
|
750
|
+
after: page.at(-1)?.sequence ?? cursor.after,
|
|
751
|
+
count: cursor.count + page.length
|
|
752
|
+
};
|
|
753
|
+
return [page, page.length === 0 || next.count >= request.limit ? Option.none() : Option.some(next)];
|
|
754
|
+
}));
|
|
755
|
+
const selection = request.selection;
|
|
756
|
+
if ("expectedTailSequence" in selection && selection.expectedTailSequence !== thread.tailSequence) return yield* storeError("selected read", "Canonical tail changed");
|
|
757
|
+
if ("throughSequence" in selection && selection.throughSequence > thread.tailSequence) return yield* storeError("selected read", "Captured sequence is ahead of canonical tail");
|
|
758
|
+
const through = "throughSequence" in selection ? selection.throughSequence : thread.tailSequence;
|
|
759
|
+
const after = request.page.afterSequence ?? 0;
|
|
760
|
+
let sources = [];
|
|
761
|
+
const one = (entry) => entry === void 0 || entry === null ? [] : [entry];
|
|
762
|
+
const latest = (entries) => one(entries[upperSequence(entries, through) - 1]);
|
|
763
|
+
switch (selection._tag) {
|
|
764
|
+
case "RecordId":
|
|
765
|
+
sources = [one(thread.byId.get(selection.recordId))];
|
|
766
|
+
break;
|
|
767
|
+
case "RunInput": {
|
|
768
|
+
const entry = thread.runInputs.get(selection.runId);
|
|
769
|
+
if (entry === null) return yield* storeError("selected read", "Ambiguous original Run input");
|
|
770
|
+
sources = [one(entry)];
|
|
771
|
+
break;
|
|
772
|
+
}
|
|
773
|
+
case "ToolDeclaration": {
|
|
774
|
+
const entry = thread.toolDeclarations.get(selection.settlementRecordId);
|
|
775
|
+
if (entry === null) return yield* storeError("selected read", "Ambiguous original tool declaration");
|
|
776
|
+
if (entry !== void 0) {
|
|
777
|
+
const payload = entry.record.payload;
|
|
778
|
+
if (payload._tag !== "ModelResponseRecorded" || !payload.toolOperations.some((operation) => toolCallSettledRecordId(payload.runId, payload.turn, operation.toolCallId) === selection.settlementRecordId)) return yield* storeError("selected read", "Invalid exact tool declaration pointer");
|
|
779
|
+
}
|
|
780
|
+
sources = [one(entry)];
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
783
|
+
case "RunEvidence":
|
|
784
|
+
sources = [thread.runRecords.get(selection.runId) ?? [], [
|
|
785
|
+
submissionInputRecordId(selection.submissionId),
|
|
786
|
+
submissionAbortRecordId(selection.submissionId),
|
|
787
|
+
submissionSettlementRecordId(selection.submissionId)
|
|
788
|
+
].flatMap((id) => one(thread.byId.get(id))).sort((a, b) => a.sequence - b.sequence)];
|
|
789
|
+
break;
|
|
790
|
+
case "OperationEvidence":
|
|
791
|
+
sources = [
|
|
792
|
+
thread.operationRecords.get(JSON.stringify([selection.runId, selection.toolCallId])) ?? [],
|
|
793
|
+
...selection.approvalToolCallIds.flatMap((toolCallId) => toolCallId === selection.toolCallId ? [] : [thread.operationRecords.get(JSON.stringify([
|
|
794
|
+
selection.runId,
|
|
795
|
+
toolCallId,
|
|
796
|
+
"approval"
|
|
797
|
+
])) ?? []]),
|
|
798
|
+
one(thread.byId.get(selection.originRecordId))
|
|
799
|
+
];
|
|
800
|
+
break;
|
|
801
|
+
case "LastAgentUpdate":
|
|
802
|
+
sources = [latest(thread.agentUpdates)];
|
|
803
|
+
break;
|
|
804
|
+
case "DeliveryPredecessor":
|
|
805
|
+
sources = [latest(thread.deliveryPredecessors)];
|
|
806
|
+
break;
|
|
807
|
+
case "LatestModelCompleted":
|
|
808
|
+
sources = [latest(thread.modelCompletions)];
|
|
809
|
+
break;
|
|
810
|
+
case "LatestApplicationInput":
|
|
811
|
+
sources = [latest(thread.applicationInputs)];
|
|
812
|
+
break;
|
|
813
|
+
case "DurableHistoryOwner":
|
|
814
|
+
sources = [one(thread.durableOwners[0])];
|
|
815
|
+
break;
|
|
816
|
+
case "PromptEvidence":
|
|
817
|
+
sources = [thread.promptEvidence];
|
|
818
|
+
break;
|
|
819
|
+
case "WorkHandoffs":
|
|
820
|
+
sources = [thread.handoffs];
|
|
821
|
+
break;
|
|
822
|
+
case "ContextWindowBoundary": {
|
|
823
|
+
let start = 0;
|
|
824
|
+
let selected;
|
|
825
|
+
while (start < selection.atSequence) {
|
|
826
|
+
const remaining = selection.atSequence - start;
|
|
827
|
+
let height = Math.floor(Math.log2(remaining));
|
|
828
|
+
while (2 ** height > remaining) height--;
|
|
829
|
+
const width = 2 ** height;
|
|
830
|
+
const entries = thread.windowBoundaries.get(`${height}:${start / width}`) ?? [];
|
|
831
|
+
const candidate = entries[upperSequence(entries, through) - 1];
|
|
832
|
+
if (candidate !== void 0 && (selected === void 0 || candidate.sequence > selected.sequence)) selected = candidate;
|
|
833
|
+
start += width;
|
|
834
|
+
}
|
|
835
|
+
sources = [one(selected)];
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
case "WorkerStop":
|
|
839
|
+
sources = [latest(thread.workerRecords.get(`stop:${selection.workerThreadId}`) ?? [])];
|
|
840
|
+
break;
|
|
841
|
+
case "WorkerExecution":
|
|
842
|
+
sources = [thread.workerRecords.get("execution:UserInputRecorded") ?? [], thread.workerRecords.get("execution:SubmissionSettled") ?? []];
|
|
843
|
+
break;
|
|
844
|
+
case "WorkerState":
|
|
845
|
+
sources = [thread.workerRecords.get("worker") ?? [], ...selection.sourceSubmissionId === void 0 ? [] : [
|
|
846
|
+
thread.workerRecords.get(`subtree:${selection.sourceSubmissionId}`) ?? [],
|
|
847
|
+
thread.workerRecords.get(`joined:${runIdForSubmission(selection.sourceSubmissionId)}`) ?? [],
|
|
848
|
+
thread.workerRecords.get(`funding:${selection.sourceSubmissionId}`) ?? []
|
|
849
|
+
]];
|
|
850
|
+
break;
|
|
851
|
+
case "LiveWorkerInputs": {
|
|
852
|
+
const index = yield* readyIndex(request.threadId, thread.tailSequence).pipe(Effect.mapError((e) => storeError("selected read", e.message)));
|
|
853
|
+
if (selection.throughSequence !== thread.tailSequence) return yield* storeError("selected read", "Live work requires the current exact tail");
|
|
854
|
+
const locators = selection.workerThreadId === void 0 ? index.liveInputs : index.inputsByWorker.get(selection.workerThreadId) ?? [];
|
|
855
|
+
const start = liveInputPosition(locators, after + 1);
|
|
856
|
+
const selected = [];
|
|
857
|
+
for (let at = start; at < Math.min(locators.length, start + request.page.limit); at++) {
|
|
858
|
+
const entry = index.entries.get(locators[at].id);
|
|
859
|
+
const origin = entry === void 0 ? void 0 : thread.byId.get(entry.originRecordId);
|
|
860
|
+
if (entry?.owner._tag !== "WorkerInput" || origin?.record.payload._tag !== "WorkerInputRequested" || origin.sequence !== locators[at].sequence || origin.record.payload.admission.origin.worker.threadId !== entry.owner.workerThreadId || origin.record.payload.admission.reportKind === "update" !== entry.owner.update) return yield* storeError("selected read", "Invalid live worker input locator or origin");
|
|
861
|
+
selected.push(origin);
|
|
862
|
+
}
|
|
863
|
+
sources = [selected];
|
|
864
|
+
break;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
return selectedStream(sources, after, through, request.page.limit);
|
|
868
|
+
}));
|
|
869
|
+
const read = (input) => Stream.unwrap(Effect.gen(function* () {
|
|
870
|
+
const request = yield* validate(ThreadReadRequest, "read", input);
|
|
871
|
+
const thread = yield* findThread(MutableRef.get(state.ref), request.threadId);
|
|
872
|
+
return readFromThread(request.threadId, thread, request);
|
|
873
|
+
}));
|
|
874
|
+
const decodePromptRecord = Schema.decodeUnknownEffect(PromptRecord);
|
|
875
|
+
const readPrompt = (input) => Stream.unwrap(Effect.gen(function* () {
|
|
876
|
+
const request = yield* validate(ThreadPromptRead, "readPrompt", input);
|
|
877
|
+
const thread = yield* findThread(MutableRef.get(state.ref), request.threadId);
|
|
878
|
+
if (request.throughSequence > thread.tailSequence) return yield* storeError("readPrompt", "Captured sequence is ahead of canonical tail");
|
|
879
|
+
const start = upperSequence(thread.promptEvidence, request.afterSequence ?? 0);
|
|
880
|
+
const records = [];
|
|
881
|
+
for (let at = start; at < Math.min(thread.promptEvidence.length, start + request.limit); at++) {
|
|
882
|
+
const entry = thread.promptEvidence[at];
|
|
883
|
+
if (entry.sequence > request.throughSequence) break;
|
|
884
|
+
const record = yield* decodePromptRecord(Schema.is(ExportedRecord)(entry.record) && Object.prototype.isPrototypeOf.call(ExportedRecord.prototype, entry.record) ? entry.record.wire : entry.record).pipe(Effect.mapError((cause) => storeError("readPrompt", "Invalid prompt record", cause)));
|
|
885
|
+
records.push({
|
|
886
|
+
threadId: request.threadId,
|
|
887
|
+
sequence: entry.sequence,
|
|
888
|
+
record
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
return Stream.fromIterable(records);
|
|
892
|
+
}));
|
|
893
|
+
const observe = (unvalidated) => Stream.unwrap(Effect.gen(function* () {
|
|
894
|
+
const request = yield* validate(ThreadObservation, "observe", unvalidated);
|
|
895
|
+
let after = yield* offsetSequence(request.threadId, request.afterOffset);
|
|
896
|
+
const subscription = yield* PubSub.subscribe(updates);
|
|
897
|
+
const drain = () => Stream.paginate(after, (cursor) => readSnapshot(request.threadId, cursor, READ_PAGE_SIZE).pipe(Effect.map((records) => {
|
|
898
|
+
after = records.at(-1)?.sequence ?? cursor;
|
|
899
|
+
return [records, records.length > 0 ? Option.some(after) : Option.none()];
|
|
900
|
+
})));
|
|
901
|
+
return drain().pipe(Stream.concat(Stream.fromEffectRepeat(PubSub.take(subscription)).pipe(Stream.flatMap(drain))));
|
|
902
|
+
}));
|
|
903
|
+
const emptyThread = () => ({
|
|
904
|
+
...emptyIndexes(),
|
|
905
|
+
tailSequence: ZERO_CANONICAL_SEQUENCE,
|
|
906
|
+
ranges: /* @__PURE__ */ new Map(),
|
|
907
|
+
rangeStarts: [],
|
|
908
|
+
archiveContents: /* @__PURE__ */ new Map(),
|
|
909
|
+
chunks: /* @__PURE__ */ new Map(),
|
|
910
|
+
batches: /* @__PURE__ */ new Map(),
|
|
911
|
+
executions: /* @__PURE__ */ new Map(),
|
|
912
|
+
executionCommits: /* @__PURE__ */ new Map(),
|
|
913
|
+
batchesByFirst: /* @__PURE__ */ new Map()
|
|
914
|
+
});
|
|
915
|
+
const makeExportReader = (idleOnly) => ThreadExporterReader.of({
|
|
916
|
+
snapshot: Effect.fnUntraced(function* (threadId, captured) {
|
|
917
|
+
const thread = MutableRef.get(state.ref).threads.get(threadId);
|
|
918
|
+
const facts = ledgerTransfer === void 0 ? {
|
|
919
|
+
idle: true,
|
|
920
|
+
admissions: 0,
|
|
921
|
+
aborts: 0,
|
|
922
|
+
approvals: 0,
|
|
923
|
+
resolutions: 0
|
|
924
|
+
} : yield* ledgerTransfer.snapshot(threadId);
|
|
925
|
+
const delivered = deliveryTransfer?.snapshot(threadId) ?? {
|
|
926
|
+
idle: true,
|
|
927
|
+
deliveries: 0
|
|
928
|
+
};
|
|
929
|
+
if (thread === void 0 && facts.admissions === 0 && delivered.deliveries === 0) return yield* ThreadNotMaterialized.make({ threadId });
|
|
930
|
+
if (idleOnly) {
|
|
931
|
+
const index = yield* readyIndex(threadId, thread?.tailSequence ?? 0).pipe(Effect.mapError((e) => storeError("export", e.message)));
|
|
932
|
+
if (owner.hasOwner(threadId) || (thread?.executions.size ?? 0) > 0 || index.entries.size > 0 || !facts.idle || !delivered.idle) return yield* ThreadExportRejected.make({
|
|
933
|
+
threadId,
|
|
934
|
+
reason: "non-idle"
|
|
935
|
+
});
|
|
936
|
+
if (captured === void 0 && thread !== void 0) yield* Effect.gen(function* () {
|
|
937
|
+
for (const runId of thread.runRecords.keys()) yield* validateClosedRun(threadId, yield* Schema.decodeEffect(RunId)(runId).pipe(Effect.orDie));
|
|
938
|
+
if (ledgerTransfer !== void 0) {
|
|
939
|
+
const ledger = ledgerTransfer;
|
|
940
|
+
yield* Stream.runForEach(ledger.submissions(threadId), (submission) => Effect.gen(function* () {
|
|
941
|
+
const admission = yield* ledger.admission(threadId, submission.submissionId);
|
|
942
|
+
if (admission === void 0) return yield* storeError("export", "Missing immutable admission");
|
|
943
|
+
yield* rebuildClosedSubmission(admission);
|
|
944
|
+
}));
|
|
945
|
+
}
|
|
946
|
+
}).pipe(Effect.provide(ThreadImportReader.layer(importReader(threadId, thread))), Effect.mapError((cause) => Schema.is(ThreadImportRejected)(cause) ? ThreadExportRejected.make({
|
|
947
|
+
threadId,
|
|
948
|
+
reason: "non-idle"
|
|
949
|
+
}) : cause));
|
|
950
|
+
}
|
|
951
|
+
return {
|
|
952
|
+
format: CURRENT_RECORD_FORMAT,
|
|
953
|
+
threadId,
|
|
954
|
+
tailSequence: thread?.tailSequence ?? ZERO_CANONICAL_SEQUENCE,
|
|
955
|
+
snapshot: {
|
|
956
|
+
admissions: facts.admissions,
|
|
957
|
+
aborts: facts.aborts,
|
|
958
|
+
approvals: facts.approvals,
|
|
959
|
+
resolutions: facts.resolutions,
|
|
960
|
+
deliveries: delivered.deliveries
|
|
961
|
+
},
|
|
962
|
+
...facts.workerSeal === void 0 ? {} : { workerSeal: facts.workerSeal }
|
|
963
|
+
};
|
|
964
|
+
}),
|
|
965
|
+
batch: Effect.fnUntraced(function* (threadId, fromSequence) {
|
|
966
|
+
const thread = yield* findThread(MutableRef.get(state.ref), threadId);
|
|
967
|
+
const batchId = thread.batchesByFirst.get(fromSequence);
|
|
968
|
+
const stored = batchId === void 0 ? void 0 : thread.batches.get(batchId);
|
|
969
|
+
if (stored === void 0 || new TextEncoder().encode(stored.batchJson).byteLength > 16777216) return yield* storeError("export", "Missing or oversized canonical batch wire");
|
|
970
|
+
const batch = yield* decodeStoredBatch(stored.batchJson, "export");
|
|
971
|
+
const records = [];
|
|
972
|
+
for (const [index, record] of batch.records.entries()) {
|
|
973
|
+
const sequence = decodeCanonicalSequence(fromSequence + index);
|
|
974
|
+
const exact = storedRecord(thread, sequence);
|
|
975
|
+
if (exact === void 0 || exact.batchId !== batch.batchId || exact.record.recordId !== record.recordId) return yield* storeError("export", "Canonical batch index differs from its wire");
|
|
976
|
+
records.push(ThreadExportRecord.make({
|
|
977
|
+
threadId,
|
|
978
|
+
batchId: batch.batchId,
|
|
979
|
+
sequence,
|
|
980
|
+
offset: observationOffset(threadId, sequence),
|
|
981
|
+
record
|
|
982
|
+
}));
|
|
983
|
+
}
|
|
984
|
+
return {
|
|
985
|
+
batches: [{
|
|
986
|
+
batchId: batch.batchId,
|
|
987
|
+
producerId: batch.producerId
|
|
988
|
+
}],
|
|
989
|
+
records
|
|
990
|
+
};
|
|
991
|
+
}),
|
|
992
|
+
facts: (threadId, section, after) => {
|
|
993
|
+
const empty = Effect.succeed({
|
|
994
|
+
facts: {
|
|
995
|
+
admissions: [],
|
|
996
|
+
commands: {
|
|
997
|
+
aborts: [],
|
|
998
|
+
approvals: [],
|
|
999
|
+
resolutions: []
|
|
1000
|
+
},
|
|
1001
|
+
deliveries: []
|
|
1002
|
+
},
|
|
1003
|
+
after: after ?? ""
|
|
1004
|
+
});
|
|
1005
|
+
return section === "deliveries" ? deliveryTransfer?.facts(threadId, after) ?? empty : ledgerTransfer?.facts(threadId, section, after) ?? empty;
|
|
1006
|
+
}
|
|
1007
|
+
});
|
|
1008
|
+
const exportReader = makeExportReader(true);
|
|
1009
|
+
const verificationReader = makeExportReader(false);
|
|
1010
|
+
const exportThread = (request) => exportThreadPage(request).pipe(Effect.provideService(ThreadExporterReader, exportReader));
|
|
1011
|
+
const verificationPage = (request) => exportThreadPage(request).pipe(Effect.provideService(ThreadExporterReader, verificationReader));
|
|
1012
|
+
const exactRunRecords = Effect.fnUntraced(function* (thread, runId) {
|
|
1013
|
+
const records = [];
|
|
1014
|
+
let bytes = 0;
|
|
1015
|
+
const facts = thread.runRecords.get(runId) ?? [];
|
|
1016
|
+
if (facts.length > MAX_RUN_EVIDENCE_RECORDS + RUN_TERMINAL_RESERVE_RECORDS + MAX_RUN_RECOVERY_SUFFIX_RECORDS) return yield* storeError("Run evidence", "Run record bounds exceeded");
|
|
1017
|
+
for (const entry of facts) {
|
|
1018
|
+
bytes += canonicalRecordBytes(entry.record);
|
|
1019
|
+
if (bytes > MAX_RUN_EVIDENCE_BYTES + MAX_RUN_TERMINAL_BYTES + MAX_RUN_RECOVERY_SUFFIX_BYTES) return yield* storeError("Run evidence", "Run byte bounds exceeded");
|
|
1020
|
+
records.push(entry);
|
|
1021
|
+
}
|
|
1022
|
+
return records.sort((a, b) => a.sequence - b.sequence);
|
|
1023
|
+
});
|
|
1024
|
+
const exactRecordReader = (threadId, thread) => ({
|
|
1025
|
+
read: (input) => Stream.unwrap(validate(ThreadReadRequest, "read snapshot", input).pipe(Effect.map((request) => readFromThread(threadId, thread, request)))),
|
|
1026
|
+
record: (id) => Effect.succeed(thread.byId.get(id)),
|
|
1027
|
+
runRecords: (id) => exactRunRecords(thread, id),
|
|
1028
|
+
execution: (id) => Effect.succeed(thread.executions.get(id)),
|
|
1029
|
+
hasAgent: (id) => Effect.succeed((thread.workerRecords.get("worker") ?? []).some(({ record }) => record.payload._tag === "ThreadCreated" && record.payload.agentId === id))
|
|
1030
|
+
});
|
|
1031
|
+
const importReader = (id, thread) => ({
|
|
1032
|
+
...exactRecordReader(id, thread),
|
|
1033
|
+
admission: (sid) => ledgerTransfer?.admission(id, sid) ?? Effect.as(Effect.void, void 0),
|
|
1034
|
+
runOwner: (runId) => runId.startsWith("run:") ? ledgerTransfer?.admission(id, Schema.decodeSync(SubmissionId)(runId.slice(4))) ?? Effect.as(Effect.void, void 0) : Effect.as(Effect.void, void 0),
|
|
1035
|
+
commands: (sid) => ledgerTransfer?.commands(sid) ?? Effect.succeed({
|
|
1036
|
+
aborts: [],
|
|
1037
|
+
approvals: [],
|
|
1038
|
+
resolutions: []
|
|
1039
|
+
}),
|
|
1040
|
+
delivery: (messageId) => deliveryTransfer?.record(id, messageId) ?? Effect.as(Effect.void, void 0)
|
|
1041
|
+
});
|
|
1042
|
+
const importThread = (pages) => captureImportSource(pages, (captured) => withMutation(Effect.gen(function* () {
|
|
1043
|
+
const progress = makeThreadImportProgress();
|
|
1044
|
+
let staged;
|
|
1045
|
+
let stagedWork = emptyWorkIndex();
|
|
1046
|
+
let stagedLedger;
|
|
1047
|
+
let stagedDelivery;
|
|
1048
|
+
let existing;
|
|
1049
|
+
yield* Stream.runForEach(captured, (input) => Effect.gen(function* () {
|
|
1050
|
+
const page = yield* prepareImportPage(progress, input).pipe(Effect.provideService(CryptoDigest.Digest, crypto));
|
|
1051
|
+
const id = page.archive.threadId;
|
|
1052
|
+
if (staged === void 0) {
|
|
1053
|
+
existing = MutableRef.get(state.ref).threads.get(id);
|
|
1054
|
+
const existingWork = MutableRef.get(workState.ref).get(id);
|
|
1055
|
+
if (existing !== void 0 && (existing.tailSequence > 0 || existing.batches.size > 0 || existing.executions.size > 0 || existing.executionCommits.size > 0 || existing.ranges.size > 0 || existing.archiveContents.size > 0) || existingWork !== void 0 && (existingWork.entries.size > 0 || existingWork.state !== "ready" || existingWork.through !== 0)) return yield* ThreadImportRejected.make({
|
|
1056
|
+
threadId: id,
|
|
1057
|
+
reason: "target-not-empty",
|
|
1058
|
+
message: "Destination canonical Thread is not empty"
|
|
1059
|
+
});
|
|
1060
|
+
if (!MutableRef.get(workState.ref).has(id) && MutableRef.get(workState.ref).size >= maxThreads) return yield* storeError("import", "Destination Thread capacity exceeded");
|
|
1061
|
+
staged = emptyThread();
|
|
1062
|
+
stagedLedger = ledgerTransfer === void 0 ? void 0 : yield* ledgerTransfer.startImport(id);
|
|
1063
|
+
stagedDelivery = deliveryTransfer === void 0 ? void 0 : yield* deliveryTransfer.startImport(id);
|
|
1064
|
+
if (page.archive.workerSeal !== void 0 && stagedLedger === void 0) return yield* ThreadImportRejected.make({
|
|
1065
|
+
threadId: id,
|
|
1066
|
+
reason: "unsupported-obligations",
|
|
1067
|
+
message: "A paired ledger is required to preserve the worker seal"
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
if (page.archive.admissions.length > 0 && stagedLedger === void 0) return yield* ThreadImportRejected.make({
|
|
1071
|
+
threadId: id,
|
|
1072
|
+
reason: "unsupported-obligations",
|
|
1073
|
+
message: "A paired ledger is required for admission restore"
|
|
1074
|
+
});
|
|
1075
|
+
if (page.archive.deliveries.length > 0 && stagedDelivery === void 0) return yield* ThreadImportRejected.make({
|
|
1076
|
+
threadId: id,
|
|
1077
|
+
reason: "unsupported-obligations",
|
|
1078
|
+
message: "A paired delivery store is required for delivery restore"
|
|
1079
|
+
});
|
|
1080
|
+
for (const batch of page.batches) {
|
|
1081
|
+
if (!canonicalBatchFitsTransfer(id, batch.batch, utf8ByteLength(batch.batchJson), 4 * Math.ceil(utf8ByteLength(id) / 3) + 36)) return yield* ThreadImportRejected.make({
|
|
1082
|
+
threadId: id,
|
|
1083
|
+
reason: "unsupported-capacity",
|
|
1084
|
+
message: "Canonical batch exceeds its bounded transfer representation"
|
|
1085
|
+
});
|
|
1086
|
+
if (staged.batches.has(batch.batch.batchId)) return yield* invalidThreadArchive("Duplicate canonical batch identity", id);
|
|
1087
|
+
const records = page.records.filter((entry) => entry.batchId === batch.batch.batchId).map((entry) => CanonicalRecordEnvelope.make({
|
|
1088
|
+
...entry,
|
|
1089
|
+
offset: observationOffset(id, entry.sequence)
|
|
1090
|
+
}));
|
|
1091
|
+
for (const entry of records) if (staged.byId.has(entry.record.recordId)) return yield* invalidThreadArchive("Duplicate canonical record identity", id);
|
|
1092
|
+
const native = prepareIndexes(staged, records);
|
|
1093
|
+
const commitWork = yield* prepareWork(stagedWork, records).pipe(Effect.provideService(CryptoDigest.Digest, crypto));
|
|
1094
|
+
retainRecords(staged, records);
|
|
1095
|
+
native.commit();
|
|
1096
|
+
staged = {
|
|
1097
|
+
...staged,
|
|
1098
|
+
...native.indexes,
|
|
1099
|
+
tailSequence: batch.lastSequence
|
|
1100
|
+
};
|
|
1101
|
+
staged.batches.set(batch.batch.batchId, {
|
|
1102
|
+
batchJson: batch.batchJson,
|
|
1103
|
+
result: AppendResult.make({
|
|
1104
|
+
firstSequence: batch.firstSequence,
|
|
1105
|
+
lastSequence: batch.lastSequence,
|
|
1106
|
+
replayed: false
|
|
1107
|
+
})
|
|
1108
|
+
});
|
|
1109
|
+
staged.batchesByFirst.set(batch.firstSequence, batch.batch.batchId);
|
|
1110
|
+
stagedWork = commitWork();
|
|
1111
|
+
}
|
|
1112
|
+
if (stagedLedger !== void 0) yield* stagedLedger.stage(page);
|
|
1113
|
+
if (stagedDelivery !== void 0) yield* stagedDelivery.stage(page);
|
|
1114
|
+
}));
|
|
1115
|
+
const result = yield* finishThreadImport(progress);
|
|
1116
|
+
if (staged === void 0) return yield* invalidThreadArchive("Missing transfer pages");
|
|
1117
|
+
const restoredThread = staged;
|
|
1118
|
+
const id = result.threadId;
|
|
1119
|
+
const fallback = {
|
|
1120
|
+
admission: () => Effect.as(Effect.void, void 0),
|
|
1121
|
+
runOwner: () => Effect.as(Effect.void, void 0),
|
|
1122
|
+
commands: () => Effect.succeed({
|
|
1123
|
+
aborts: [],
|
|
1124
|
+
approvals: [],
|
|
1125
|
+
resolutions: []
|
|
1126
|
+
})
|
|
1127
|
+
};
|
|
1128
|
+
const reader = {
|
|
1129
|
+
...exactRecordReader(id, restoredThread),
|
|
1130
|
+
...stagedLedger?.reader ?? fallback,
|
|
1131
|
+
delivery: stagedDelivery?.record ?? (() => Effect.as(Effect.void, void 0))
|
|
1132
|
+
};
|
|
1133
|
+
return yield* Effect.gen(function* () {
|
|
1134
|
+
for (const runId of restoredThread.runRecords.keys()) {
|
|
1135
|
+
yield* verifyRunContinuations(yield* reader.runRecords(yield* Schema.decodeEffect(RunId)(runId).pipe(Effect.orDie)), { verifyContext: false }).pipe(Effect.mapError((e) => invalidThreadArchive(e.message, id)));
|
|
1136
|
+
yield* validateClosedRun(id, yield* Schema.decodeEffect(RunId)(runId).pipe(Effect.orDie));
|
|
1137
|
+
}
|
|
1138
|
+
let lastInputQueue = -1;
|
|
1139
|
+
for (let sequence = 1; sequence <= restoredThread.tailSequence; sequence++) {
|
|
1140
|
+
const entry = storedRecord(restoredThread, sequence);
|
|
1141
|
+
if (entry === void 0) return yield* invalidThreadArchive("Incomplete canonical staging", id);
|
|
1142
|
+
yield* verifyImportedReferences(entry);
|
|
1143
|
+
const payload = entry.record.payload;
|
|
1144
|
+
if (payload._tag === "UserInputRecorded" && payload.submissionId !== void 0) {
|
|
1145
|
+
const admission = yield* reader.admission(payload.submissionId);
|
|
1146
|
+
if (admission === void 0 || admission.queueSequence <= lastInputQueue) return yield* invalidThreadArchive("Canonical inputs violate immutable admission order", id);
|
|
1147
|
+
lastInputQueue = admission.queueSequence;
|
|
1148
|
+
}
|
|
1149
|
+
if (payload._tag === "UserInputRecorded" && payload.submissionId !== void 0 && entry.record.recordId !== submissionInputRecordId(payload.submissionId)) return yield* invalidThreadArchive("Canonical input identity is ambiguous", id);
|
|
1150
|
+
if (payload._tag === "SubmissionSettled" && entry.record.recordId !== submissionSettlementRecordId(payload.submissionId)) return yield* invalidThreadArchive("Canonical settlement identity is ambiguous", id);
|
|
1151
|
+
if (payload._tag !== "WorkerInputCompleted" && "submissionId" in payload && payload.submissionId !== void 0 && (yield* reader.admission(payload.submissionId)) === void 0) return yield* invalidThreadArchive("Canonical submission has no admission", id);
|
|
1152
|
+
}
|
|
1153
|
+
if (stagedWork.entries.size > 0) return yield* ThreadImportRejected.make({
|
|
1154
|
+
threadId: id,
|
|
1155
|
+
reason: "unsupported-obligations",
|
|
1156
|
+
message: "Transfer contains unresolved work"
|
|
1157
|
+
});
|
|
1158
|
+
const commitLedger = stagedLedger === void 0 ? void 0 : yield* stagedLedger.prepareCommit(progress.manifest?.workerSeal);
|
|
1159
|
+
const commitDelivery = stagedDelivery === void 0 ? void 0 : yield* stagedDelivery.prepareCommit;
|
|
1160
|
+
const installed = restoredThread;
|
|
1161
|
+
yield* Effect.uninterruptible(Effect.sync(() => {
|
|
1162
|
+
commitLedger?.();
|
|
1163
|
+
commitDelivery?.();
|
|
1164
|
+
publishWork(id, stagedWork);
|
|
1165
|
+
MutableRef.get(state.ref).threads.set(id, installed);
|
|
1166
|
+
}).pipe(Effect.andThen(PubSub.publish(updates, void 0))));
|
|
1167
|
+
return result;
|
|
1168
|
+
}).pipe(Effect.provide(ThreadImportReader.layer(reader)), Effect.provideService(ThreadDeliveryImportReader, {
|
|
1169
|
+
admission: (threadId, sid) => threadId === id ? reader.admission(sid) : ledgerTransfer?.admission(threadId, sid) ?? Effect.as(Effect.void, void 0),
|
|
1170
|
+
record: (threadId, recordId) => Effect.succeed(threadId === id ? restoredThread.byId.get(recordId)?.record : MutableRef.get(state.ref).threads.get(threadId)?.byId.get(recordId)?.record)
|
|
1171
|
+
}));
|
|
1172
|
+
}).pipe(Effect.provideService(CryptoDigest.Digest, crypto))));
|
|
1173
|
+
const inspectTail = Effect.fnUntraced(function* (unvalidated) {
|
|
1174
|
+
const request = yield* validate(ThreadTailRequest, "inspectTail", unvalidated);
|
|
1175
|
+
const thread = yield* Ref.get(state).pipe(Effect.flatMap((current) => findThread(current, request.threadId)));
|
|
1176
|
+
return ThreadTail.make({
|
|
1177
|
+
threadId: request.threadId,
|
|
1178
|
+
tailSequence: thread.tailSequence
|
|
1179
|
+
});
|
|
1180
|
+
});
|
|
1181
|
+
const readIdentity = Effect.fnUntraced(function* (unvalidated) {
|
|
1182
|
+
const request = yield* validate(ThreadIdentityRequest, "readIdentity", unvalidated);
|
|
1183
|
+
const thread = yield* Ref.get(state).pipe(Effect.flatMap((current) => findThread(current, request.threadId)));
|
|
1184
|
+
const selected = [
|
|
1185
|
+
storedRecord(thread, 1),
|
|
1186
|
+
thread.byId.get(workerOriginRecordId(request.threadId)),
|
|
1187
|
+
thread.byId.get(subagentLineageRecordId(request.threadId))
|
|
1188
|
+
].filter((entry) => entry !== void 0);
|
|
1189
|
+
return yield* ThreadIdentity.makeEffect({
|
|
1190
|
+
threadId: request.threadId,
|
|
1191
|
+
tailSequence: thread.tailSequence,
|
|
1192
|
+
hasAdmissions: ledgerTransfer !== void 0 && (yield* ledgerTransfer.snapshot(request.threadId)).admissions > 0,
|
|
1193
|
+
records: selected.filter((entry, index) => selected.findIndex((other) => other.record.recordId === entry.record.recordId) === index)
|
|
1194
|
+
}).pipe(Effect.mapError((cause) => storeError("readIdentity", "Invalid canonical identity", cause)));
|
|
1195
|
+
});
|
|
1196
|
+
const verifyRange = Effect.fnUntraced(function* (thread, range, source) {
|
|
1197
|
+
let sequence = range.firstSequence;
|
|
1198
|
+
let bytes = 0;
|
|
1199
|
+
let batches = 0;
|
|
1200
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1201
|
+
while (sequence <= range.lastSequence) {
|
|
1202
|
+
const id = thread.batchesByFirst.get(sequence);
|
|
1203
|
+
const batch = id === void 0 ? void 0 : thread.batches.get(id);
|
|
1204
|
+
const text = id === void 0 ? void 0 : source === void 0 ? batch?.batchJson : source.get(id);
|
|
1205
|
+
if (id === void 0 || batch === void 0 || text === void 0 || batch.result.lastSequence > range.lastSequence) return yield* storeError("verify range", "Incomplete canonical batch range");
|
|
1206
|
+
bytes += new TextEncoder().encode(text).byteLength;
|
|
1207
|
+
batches++;
|
|
1208
|
+
if (bytes > MAX_ARCHIVE_RANGE_BYTES || batches > MAX_ARCHIVE_RANGE_RECORDS || text !== batch.batchJson) return yield* storeError("verify range", "Range wire or bounds differ from canonical storage");
|
|
1209
|
+
const wire = yield* Schema.decodeEffect(Schema.fromJsonString(ExportBatch))(text).pipe(Effect.mapError((cause) => storeError("verify range", "Invalid range wire", cause)));
|
|
1210
|
+
if (wire.batchId !== id || batch.result.firstSequence !== sequence || batch.result.lastSequence !== sequence + wire.records.length - 1) return yield* storeError("verify range", "Canonical batch span or identity differs");
|
|
1211
|
+
for (const [index, record] of wire.records.entries()) {
|
|
1212
|
+
const expected = storedRecord(thread, sequence + index);
|
|
1213
|
+
if (expected === void 0 || expected.threadId !== range.threadId || expected.sequence !== sequence + index || expected.batchId !== id || expected.record.recordId !== record.recordId) return yield* storeError("verify range", "Canonical record identity or order differs");
|
|
1214
|
+
const canonical = yield* Schema.encodeEffect(ReadRecord)(expected.record).pipe(Effect.mapError((cause) => storeError("verify range", "Invalid canonical record", cause)));
|
|
1215
|
+
const archived = yield* Schema.encodeEffect(ExportRecord)(record).pipe(Effect.mapError((cause) => storeError("verify range", "Invalid archive record", cause)));
|
|
1216
|
+
if (canonicalJson(canonical) !== canonicalJson(archived)) return yield* storeError("verify range", "Archive and canonical record bytes differ");
|
|
1217
|
+
}
|
|
1218
|
+
captured.set(id, text);
|
|
1219
|
+
sequence = decodeCanonicalSequence(batch.result.lastSequence + 1);
|
|
1220
|
+
}
|
|
1221
|
+
if (bytes !== range.byteCount || batches !== range.batchCount || range.recordCount !== range.lastSequence - range.firstSequence + 1) return yield* storeError("verify range", "Range spans or counts differ");
|
|
1222
|
+
return captured;
|
|
1223
|
+
});
|
|
1224
|
+
const archiveTarget = Effect.fnUntraced(function* (request) {
|
|
1225
|
+
return yield* findThread(MutableRef.get(state.ref), request.threadId);
|
|
1226
|
+
});
|
|
1227
|
+
const archives = {
|
|
1228
|
+
page: Effect.fnUntraced(function* (unvalidated) {
|
|
1229
|
+
const request = yield* validate(ThreadArchiveRangeRead, "range page", unvalidated);
|
|
1230
|
+
const thread = yield* findThread(MutableRef.get(state.ref), request.threadId);
|
|
1231
|
+
let low = 0;
|
|
1232
|
+
let high = thread.rangeStarts.length;
|
|
1233
|
+
while (low < high) {
|
|
1234
|
+
const middle = Math.floor((low + high) / 2);
|
|
1235
|
+
const range = thread.ranges.get(thread.rangeStarts[middle]);
|
|
1236
|
+
if (range === void 0) return yield* storeError("page ranges", "Range locator has no exact range");
|
|
1237
|
+
if (range.lastSequence <= (request.afterSequence ?? 0)) low = middle + 1;
|
|
1238
|
+
else high = middle;
|
|
1239
|
+
}
|
|
1240
|
+
const ranges = [];
|
|
1241
|
+
const limit = request.limit ?? 32;
|
|
1242
|
+
for (let at = low; at < Math.min(thread.rangeStarts.length, low + limit); at++) {
|
|
1243
|
+
const range = thread.ranges.get(thread.rangeStarts[at]);
|
|
1244
|
+
if (range === void 0) return yield* storeError("page ranges", "Range locator has no exact range");
|
|
1245
|
+
ranges.push(range);
|
|
1246
|
+
}
|
|
1247
|
+
const afterSequence = low + ranges.length < thread.rangeStarts.length ? ranges.at(-1)?.lastSequence : void 0;
|
|
1248
|
+
return {
|
|
1249
|
+
ranges,
|
|
1250
|
+
...afterSequence === void 0 ? {} : { afterSequence }
|
|
1251
|
+
};
|
|
1252
|
+
}),
|
|
1253
|
+
seal: (unvalidated) => withMutation(Effect.gen(function* () {
|
|
1254
|
+
const request = yield* validate(ThreadArchiveRangeSeal, "seal range", unvalidated);
|
|
1255
|
+
const thread = yield* archiveTarget(request);
|
|
1256
|
+
const previousStart = thread.rangeStarts.at(-1);
|
|
1257
|
+
const previous = previousStart === void 0 ? void 0 : thread.ranges.get(previousStart);
|
|
1258
|
+
if (previousStart !== void 0 && previous === void 0) return yield* storeError("seal range", "Range locator has no exact range");
|
|
1259
|
+
const firstSequence = (previous?.lastSequence ?? 0) + 1;
|
|
1260
|
+
if (firstSequence > thread.tailSequence) return Option.none();
|
|
1261
|
+
let nextSequence = firstSequence;
|
|
1262
|
+
let byteCount = 0;
|
|
1263
|
+
let batchCount = 0;
|
|
1264
|
+
while (nextSequence <= thread.tailSequence) {
|
|
1265
|
+
const batchId = thread.batchesByFirst.get(nextSequence);
|
|
1266
|
+
const batch = batchId === void 0 ? void 0 : thread.batches.get(batchId);
|
|
1267
|
+
if (batch === void 0) return yield* storeError("seal range", "Missing exact canonical batch");
|
|
1268
|
+
const bytes = utf8ByteLength(batch.batchJson);
|
|
1269
|
+
if (batchCount > 0 && (batch.result.lastSequence - firstSequence + 1 > MAX_ARCHIVE_RANGE_RECORDS || byteCount + bytes > MAX_ARCHIVE_RANGE_BYTES)) break;
|
|
1270
|
+
byteCount += bytes;
|
|
1271
|
+
batchCount++;
|
|
1272
|
+
nextSequence = batch.result.lastSequence + 1;
|
|
1273
|
+
}
|
|
1274
|
+
const range = ThreadArchiveRange.make({
|
|
1275
|
+
format: "effect-agent/thread-range@2",
|
|
1276
|
+
threadId: request.threadId,
|
|
1277
|
+
firstSequence: decodeCanonicalSequence(firstSequence),
|
|
1278
|
+
lastSequence: decodeCanonicalSequence(nextSequence - 1),
|
|
1279
|
+
recordCount: nextSequence - firstSequence,
|
|
1280
|
+
batchCount,
|
|
1281
|
+
byteCount,
|
|
1282
|
+
state: "sealed"
|
|
1283
|
+
});
|
|
1284
|
+
yield* verifyRange(thread, range);
|
|
1285
|
+
thread.ranges.set(firstSequence, range);
|
|
1286
|
+
thread.rangeStarts.push(firstSequence);
|
|
1287
|
+
return Option.some(range);
|
|
1288
|
+
})),
|
|
1289
|
+
verify: Effect.fnUntraced(function* (unvalidated) {
|
|
1290
|
+
const request = yield* validate(ThreadArchiveRangeRequest, "verify range", unvalidated);
|
|
1291
|
+
const thread = yield* findThread(MutableRef.get(state.ref), request.threadId);
|
|
1292
|
+
const range = thread.ranges.get(request.firstSequence);
|
|
1293
|
+
if (range === void 0) return yield* storeError("verify range", "Unknown sealed range");
|
|
1294
|
+
yield* verifyRange(thread, range, range.state === "archived" ? thread.archiveContents.get(range.firstSequence) : void 0);
|
|
1295
|
+
if (range.state === "archived" && !thread.archiveContents.has(range.firstSequence)) return yield* storeError("verify range", "Published archive contents are missing");
|
|
1296
|
+
return range;
|
|
1297
|
+
}),
|
|
1298
|
+
archive: (unvalidated) => withMutation(Effect.gen(function* () {
|
|
1299
|
+
const request = yield* validate(ThreadArchiveRangePublish, "archive range", unvalidated);
|
|
1300
|
+
const thread = yield* archiveTarget(request);
|
|
1301
|
+
const range = thread.ranges.get(request.firstSequence);
|
|
1302
|
+
if (range === void 0) return yield* storeError("archive range", "Unknown sealed range");
|
|
1303
|
+
if (range.state === "archived") {
|
|
1304
|
+
const contents = thread.archiveContents.get(range.firstSequence);
|
|
1305
|
+
if (contents === void 0) return yield* storeError("archive range", "Published archive contents are missing");
|
|
1306
|
+
yield* verifyRange(thread, range, contents);
|
|
1307
|
+
return range;
|
|
1308
|
+
}
|
|
1309
|
+
const contents = yield* verifyRange(thread, range);
|
|
1310
|
+
yield* verifyRange(thread, range, contents);
|
|
1311
|
+
const published = ThreadArchiveRange.make({
|
|
1312
|
+
...range,
|
|
1313
|
+
state: "archived",
|
|
1314
|
+
locator: `memory:${encodeURIComponent(request.threadId)}:${range.firstSequence}`
|
|
1315
|
+
});
|
|
1316
|
+
thread.archiveContents.set(range.firstSequence, contents);
|
|
1317
|
+
thread.ranges.set(range.firstSequence, published);
|
|
1318
|
+
return published;
|
|
1319
|
+
}))
|
|
1320
|
+
};
|
|
1321
|
+
const readWorkerCapacity = Effect.fnUntraced(function* (unvalidated) {
|
|
1322
|
+
const request = yield* validate(ThreadWorkerCapacityRequest, "worker capacity", unvalidated);
|
|
1323
|
+
const thread = yield* findThread(MutableRef.get(state.ref), request.threadId);
|
|
1324
|
+
if (request.expectedTailSequence !== thread.tailSequence) return yield* storeError("worker capacity", "Canonical tail changed");
|
|
1325
|
+
const index = yield* readyIndex(request.threadId, thread.tailSequence).pipe(Effect.mapError((e) => storeError("worker capacity", e.message)));
|
|
1326
|
+
const worker = index.workers.get(request.workerThreadId);
|
|
1327
|
+
return ThreadWorkerCapacity.make({
|
|
1328
|
+
threadId: request.threadId,
|
|
1329
|
+
tailSequence: thread.tailSequence,
|
|
1330
|
+
activeWorkers: Math.min(index.workers.size, request.activeLimit + 1),
|
|
1331
|
+
workerActive: worker !== void 0,
|
|
1332
|
+
pendingInputs: Math.min(request.update ? worker?.update ?? 0 : worker?.ordinary ?? 0, request.pendingLimit + 1)
|
|
1333
|
+
});
|
|
1334
|
+
});
|
|
1335
|
+
const threadStore = ThreadStore.of({
|
|
1336
|
+
work,
|
|
1337
|
+
archives,
|
|
1338
|
+
verification: { verify: (unvalidated) => withMutation(Effect.gen(function* () {
|
|
1339
|
+
const request = yield* validate(ThreadVerificationRequest, "verify Thread", unvalidated);
|
|
1340
|
+
const thread = yield* findThread(MutableRef.get(state.ref), request.threadId);
|
|
1341
|
+
const id = request.threadId;
|
|
1342
|
+
const reader = importReader(id, thread);
|
|
1343
|
+
const submissions = () => ledgerTransfer?.submissions(id) ?? Stream.empty;
|
|
1344
|
+
const runs = Stream.fromIterable(thread.runRecords.keys()).pipe(Stream.map((runId) => Schema.decodeSync(RunId)(runId)));
|
|
1345
|
+
return yield* verifyThreadInvariants({
|
|
1346
|
+
threadId: id,
|
|
1347
|
+
runs,
|
|
1348
|
+
executions: Stream.fromIterable(thread.executions.values()),
|
|
1349
|
+
submissions: submissions(),
|
|
1350
|
+
pages: streamExport({ threadId: id }).pipe(Stream.provideService(ThreadExportSource, { export: verificationPage }), Stream.mapError((cause) => Schema.is(ThreadExportRejected)(cause) ? storeError("verify Thread", "Internal verification snapshot changed") : cause)),
|
|
1351
|
+
...request.requireAllSettled === void 0 ? {} : { requireAllSettled: request.requireAllSettled }
|
|
1352
|
+
}).pipe(Effect.provide(ThreadImportReader.layer(reader)), Effect.provideService(CryptoDigest.Digest, crypto));
|
|
1353
|
+
})) },
|
|
1354
|
+
readWorkerCapacity,
|
|
1355
|
+
readIdentity,
|
|
1356
|
+
countPeerMessages,
|
|
1357
|
+
materialize: (request) => withMutation(materialize(request)),
|
|
1358
|
+
append,
|
|
1359
|
+
readExecution: (request) => withMutation(Effect.gen(function* () {
|
|
1360
|
+
const thread = (yield* Ref.get(state)).threads.get(request.threadId);
|
|
1361
|
+
if (thread === void 0) return yield* ThreadNotMaterialized.make({ threadId: request.threadId });
|
|
1362
|
+
return Option.fromUndefinedOr(thread.executions.get(request.runId));
|
|
1363
|
+
})),
|
|
1364
|
+
read,
|
|
1365
|
+
readPrompt,
|
|
1366
|
+
observe,
|
|
1367
|
+
export: (request) => checkExportSource(request.threadId).pipe(Effect.andThen(withMutation(exportThread(request)))),
|
|
1368
|
+
inspectTail
|
|
1369
|
+
});
|
|
1370
|
+
return Context.make(ThreadStore, threadStore).pipe(Context.add(StorageOwner, owner), Context.add(ThreadImport, { import: importThread }), Context.add(MemoryThreadStoreKernel, {
|
|
1371
|
+
owner,
|
|
1372
|
+
withMutation,
|
|
1373
|
+
checkThreadCapacity: (threadId) => Effect.suspend(() => !MutableRef.get(workState.ref).has(threadId) && MutableRef.get(workState.ref).size >= maxThreads ? Effect.fail(storeError("Thread capacity", "Retained Thread quota exceeded")) : Effect.void),
|
|
1374
|
+
initializeWork: (threadId) => {
|
|
1375
|
+
if (!MutableRef.get(state.ref).threads.has(threadId) && !MutableRef.get(workState.ref).has(threadId)) publishWork(threadId, emptyWorkIndex());
|
|
1376
|
+
},
|
|
1377
|
+
registerWorkOwner: (kind, owner) => withMutation(Effect.gen(function* () {
|
|
1378
|
+
if (workOwners.has(kind)) return yield* Effect.die(storeError("initialize", `MemoryThreadStore already has a ${kind} work owner`));
|
|
1379
|
+
workOwners.set(kind, owner);
|
|
1380
|
+
})),
|
|
1381
|
+
registerDeliveryWriter: (writer) => withMutation(Effect.gen(function* () {
|
|
1382
|
+
if (deliveryWriter !== void 0) return yield* Effect.die(storeError("initialize", "MemoryThreadStore already has a delivery writer"));
|
|
1383
|
+
deliveryWriter = writer;
|
|
1384
|
+
})),
|
|
1385
|
+
registerLedgerTransfer: (transfer) => withMutation(Effect.gen(function* () {
|
|
1386
|
+
if (ledgerTransfer !== void 0) return yield* Effect.die(storeError("initialize", "MemoryThreadStore already has a paired SubmissionLedger"));
|
|
1387
|
+
ledgerTransfer = transfer;
|
|
1388
|
+
})),
|
|
1389
|
+
registerDeliveryTransfer: (transfer) => withMutation(Effect.gen(function* () {
|
|
1390
|
+
if (deliveryTransfer !== void 0) return yield* Effect.die(storeError("initialize", "MemoryThreadStore already has a paired delivery store"));
|
|
1391
|
+
deliveryTransfer = transfer;
|
|
1392
|
+
})),
|
|
1393
|
+
prepareAppend,
|
|
1394
|
+
appendPrepared,
|
|
1395
|
+
record: (threadId, recordId) => Ref.get(state).pipe(Effect.map((current) => current.threads.get(threadId)?.byId.get(recordId)?.record)),
|
|
1396
|
+
toolCallResults: (threadId, runId, toolCallId) => Ref.get(state).pipe(Effect.map((current) => (current.threads.get(threadId)?.operationRecords.get(JSON.stringify([
|
|
1397
|
+
runId,
|
|
1398
|
+
toolCallId,
|
|
1399
|
+
"settled"
|
|
1400
|
+
])) ?? []).slice(0, 2).map((entry) => entry.record))),
|
|
1401
|
+
tail: (threadId) => inspectTail(ThreadTailRequest.make({ threadId }))
|
|
1402
|
+
}));
|
|
1403
|
+
});
|
|
1404
|
+
/**
|
|
1405
|
+
* In-memory canonical Thread persistence. Durable accepted work is served by the separate
|
|
1406
|
+
* SubmissionLedger port; this Layer provides ThreadStore, ThreadReader, and ThreadImport.
|
|
1407
|
+
* Importing admissions requires a MemorySubmissionLedger paired with this store.
|
|
1408
|
+
* Publishing canonical messages requires a paired MemoryMessageDeliveryStore.
|
|
1409
|
+
*/
|
|
1410
|
+
const MemoryThreadStoreLive = ThreadReader.layer().pipe(Layer.provideMerge(Layer.effectContext(makeThreadStore)));
|
|
1411
|
+
/** Configure a finite retained Thread capacity. Invalid construction options throw immediately. */
|
|
1412
|
+
const memoryThreadStoreLayer = (options = {}) => MemoryThreadStoreLive.pipe(Layer.provide(Layer.succeed(ThreadCapacity)(Schema.decodeSync(Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(65536)))(options.maxThreads ?? MAX_THREADS))));
|
|
1413
|
+
export { MemoryThreadStore_exports as n, memoryThreadStoreLayer as r, MemoryThreadStoreLive as t };
|
|
1414
|
+
|
|
1415
|
+
//# sourceMappingURL=MemoryThreadStore-Dtwe-7h4.mjs.map
|