@earendil-works/pi-agent-core 0.83.0 → 0.84.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 (140) hide show
  1. package/README.md +9 -3
  2. package/dist/agent.d.ts +3 -1
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +6 -0
  5. package/dist/agent.js.map +1 -1
  6. package/dist/harness/agent-harness.d.ts +452 -85
  7. package/dist/harness/agent-harness.d.ts.map +1 -1
  8. package/dist/harness/agent-harness.js +204 -917
  9. package/dist/harness/agent-harness.js.map +1 -1
  10. package/dist/harness/compaction/branch-summarization.d.ts +13 -6
  11. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
  12. package/dist/harness/compaction/branch-summarization.js +11 -15
  13. package/dist/harness/compaction/branch-summarization.js.map +1 -1
  14. package/dist/harness/compaction/compaction.d.ts +14 -17
  15. package/dist/harness/compaction/compaction.d.ts.map +1 -1
  16. package/dist/harness/compaction/compaction.js +23 -36
  17. package/dist/harness/compaction/compaction.js.map +1 -1
  18. package/dist/harness/env/nodejs.d.ts +1 -0
  19. package/dist/harness/env/nodejs.d.ts.map +1 -1
  20. package/dist/harness/env/nodejs.js +23 -7
  21. package/dist/harness/env/nodejs.js.map +1 -1
  22. package/dist/harness/messages.d.ts +3 -3
  23. package/dist/harness/messages.d.ts.map +1 -1
  24. package/dist/harness/messages.js +3 -3
  25. package/dist/harness/messages.js.map +1 -1
  26. package/dist/harness/prompt-templates.d.ts.map +1 -1
  27. package/dist/harness/prompt-templates.js +4 -9
  28. package/dist/harness/prompt-templates.js.map +1 -1
  29. package/dist/harness/reducer.d.ts +100 -0
  30. package/dist/harness/reducer.d.ts.map +1 -0
  31. package/dist/harness/reducer.js +415 -0
  32. package/dist/harness/reducer.js.map +1 -0
  33. package/dist/harness/result.d.ts +40 -0
  34. package/dist/harness/result.d.ts.map +1 -0
  35. package/dist/harness/result.js +41 -0
  36. package/dist/harness/result.js.map +1 -0
  37. package/dist/harness/session/context.d.ts +22 -0
  38. package/dist/harness/session/context.d.ts.map +1 -0
  39. package/dist/harness/session/context.js +67 -0
  40. package/dist/harness/session/context.js.map +1 -0
  41. package/dist/harness/session/index.d.ts +7 -0
  42. package/dist/harness/session/index.d.ts.map +1 -0
  43. package/dist/harness/session/index.js +6 -0
  44. package/dist/harness/session/index.js.map +1 -0
  45. package/dist/harness/session/jsonl/codec.d.ts +8 -0
  46. package/dist/harness/session/jsonl/codec.d.ts.map +1 -0
  47. package/dist/harness/session/jsonl/codec.js +190 -0
  48. package/dist/harness/session/jsonl/codec.js.map +1 -0
  49. package/dist/harness/session/jsonl/errors.d.ts +5 -0
  50. package/dist/harness/session/jsonl/errors.d.ts.map +1 -0
  51. package/dist/harness/session/jsonl/errors.js +11 -0
  52. package/dist/harness/session/jsonl/errors.js.map +1 -0
  53. package/dist/harness/session/jsonl/repo.d.ts +23 -0
  54. package/dist/harness/session/jsonl/repo.d.ts.map +1 -0
  55. package/dist/harness/session/jsonl/repo.js +132 -0
  56. package/dist/harness/session/jsonl/repo.js.map +1 -0
  57. package/dist/harness/session/jsonl/storage.d.ts +43 -0
  58. package/dist/harness/session/jsonl/storage.d.ts.map +1 -0
  59. package/dist/harness/session/jsonl/storage.js +208 -0
  60. package/dist/harness/session/jsonl/storage.js.map +1 -0
  61. package/dist/harness/session/jsonl/types.d.ts +38 -0
  62. package/dist/harness/session/jsonl/types.d.ts.map +1 -0
  63. package/dist/harness/session/jsonl/types.js +2 -0
  64. package/dist/harness/session/jsonl/types.js.map +1 -0
  65. package/dist/harness/session/jsonl.d.ts +3 -0
  66. package/dist/harness/session/jsonl.d.ts.map +1 -0
  67. package/dist/harness/session/jsonl.js +2 -0
  68. package/dist/harness/session/jsonl.js.map +1 -0
  69. package/dist/harness/session/memory.d.ts +44 -0
  70. package/dist/harness/session/memory.d.ts.map +1 -0
  71. package/dist/harness/session/memory.js +141 -0
  72. package/dist/harness/session/memory.js.map +1 -0
  73. package/dist/harness/session/search.d.ts +19 -0
  74. package/dist/harness/session/search.d.ts.map +1 -0
  75. package/dist/harness/session/search.js +42 -0
  76. package/dist/harness/session/search.js.map +1 -0
  77. package/dist/harness/session/session.d.ts +43 -42
  78. package/dist/harness/session/session.d.ts.map +1 -1
  79. package/dist/harness/session/session.js +187 -228
  80. package/dist/harness/session/session.js.map +1 -1
  81. package/dist/harness/session/state.d.ts +65 -0
  82. package/dist/harness/session/state.d.ts.map +1 -0
  83. package/dist/harness/session/state.js +319 -0
  84. package/dist/harness/session/state.js.map +1 -0
  85. package/dist/harness/session/testing/conformance.d.ts +4 -0
  86. package/dist/harness/session/testing/conformance.d.ts.map +1 -0
  87. package/dist/harness/session/testing/conformance.js +743 -0
  88. package/dist/harness/session/testing/conformance.js.map +1 -0
  89. package/dist/harness/session/testing/index.d.ts +3 -0
  90. package/dist/harness/session/testing/index.d.ts.map +1 -0
  91. package/dist/harness/session/testing/index.js +2 -0
  92. package/dist/harness/session/testing/index.js.map +1 -0
  93. package/dist/harness/session/testing/types.d.ts +14 -0
  94. package/dist/harness/session/testing/types.d.ts.map +1 -0
  95. package/dist/harness/session/testing/types.js +2 -0
  96. package/dist/harness/session/testing/types.js.map +1 -0
  97. package/dist/harness/session/types.d.ts +333 -0
  98. package/dist/harness/session/types.d.ts.map +1 -0
  99. package/dist/harness/session/types.js +10 -0
  100. package/dist/harness/session/types.js.map +1 -0
  101. package/dist/harness/skills.d.ts.map +1 -1
  102. package/dist/harness/skills.js +21 -19
  103. package/dist/harness/skills.js.map +1 -1
  104. package/dist/harness/telemetry.d.ts +1221 -0
  105. package/dist/harness/telemetry.d.ts.map +1 -0
  106. package/dist/harness/telemetry.js +508 -0
  107. package/dist/harness/telemetry.js.map +1 -0
  108. package/dist/harness/types.d.ts +6 -459
  109. package/dist/harness/types.d.ts.map +1 -1
  110. package/dist/harness/types.js +0 -19
  111. package/dist/harness/types.js.map +1 -1
  112. package/dist/index.d.ts +10 -9
  113. package/dist/index.d.ts.map +1 -1
  114. package/dist/index.js +7 -8
  115. package/dist/index.js.map +1 -1
  116. package/dist/proxy.d.ts +1 -1
  117. package/dist/proxy.d.ts.map +1 -1
  118. package/dist/proxy.js +1 -0
  119. package/dist/proxy.js.map +1 -1
  120. package/package.json +9 -2
  121. package/dist/harness/session/jsonl-repo.d.ts +0 -26
  122. package/dist/harness/session/jsonl-repo.d.ts.map +0 -1
  123. package/dist/harness/session/jsonl-repo.js +0 -103
  124. package/dist/harness/session/jsonl-repo.js.map +0 -1
  125. package/dist/harness/session/jsonl-storage.d.ts +0 -42
  126. package/dist/harness/session/jsonl-storage.d.ts.map +0 -1
  127. package/dist/harness/session/jsonl-storage.js +0 -293
  128. package/dist/harness/session/jsonl-storage.js.map +0 -1
  129. package/dist/harness/session/memory-repo.d.ts +0 -18
  130. package/dist/harness/session/memory-repo.d.ts.map +0 -1
  131. package/dist/harness/session/memory-repo.js +0 -42
  132. package/dist/harness/session/memory-repo.js.map +0 -1
  133. package/dist/harness/session/memory-storage.d.ts +0 -33
  134. package/dist/harness/session/memory-storage.d.ts.map +0 -1
  135. package/dist/harness/session/memory-storage.js +0 -168
  136. package/dist/harness/session/memory-storage.js.map +0 -1
  137. package/dist/harness/session/repo-utils.d.ts +0 -11
  138. package/dist/harness/session/repo-utils.d.ts.map +0 -1
  139. package/dist/harness/session/repo-utils.js +0 -39
  140. package/dist/harness/session/repo-utils.js.map +0 -1
@@ -0,0 +1,415 @@
1
+ import { Guard } from "typebox/guard";
2
+ export class RecordLogCorruption extends Error {
3
+ reason;
4
+ constructor(reason, message) {
5
+ super(message);
6
+ this.name = "RecordLogCorruption";
7
+ this.reason = reason;
8
+ }
9
+ }
10
+ function corrupt(reason, message) {
11
+ throw new RecordLogCorruption(reason, message);
12
+ }
13
+ function hasRunId(record) {
14
+ return "runId" in record && typeof record.runId === "string";
15
+ }
16
+ function matchesProvisionedEntry(entry, target) {
17
+ const { parentId: _parentId, seq: _seq, timestamp: _timestamp, ...payload } = entry;
18
+ return Guard.IsDeepEqual(payload, target);
19
+ }
20
+ function validateExactProvisionedEntry(entriesById, target) {
21
+ const entry = entriesById.get(target.id);
22
+ if (entry && !matchesProvisionedEntry(entry, target)) {
23
+ corrupt("provisioned_entry_mismatch", `Provisioned entry ${target.id} exists with content different from its intent`);
24
+ }
25
+ }
26
+ function validateResultEntry(entriesById, resultEntryId, matches, description) {
27
+ const entry = entriesById.get(resultEntryId);
28
+ if (entry && !matches(entry)) {
29
+ corrupt("provisioned_entry_mismatch", `Provisioned ${description} entry ${resultEntryId} exists with different content`);
30
+ }
31
+ }
32
+ function validateAttemptReason(record) {
33
+ const reason = record.compactionReason;
34
+ if (record.step === "compaction") {
35
+ if (reason !== "manual" && reason !== "threshold" && reason !== "overflow") {
36
+ corrupt("invalid_compaction_reason", `Compaction attempt ${record.id} has no valid compaction reason`);
37
+ }
38
+ }
39
+ else if (reason !== undefined) {
40
+ corrupt("invalid_compaction_reason", `${record.step} attempt ${record.id} has a compaction reason`);
41
+ }
42
+ }
43
+ function validateAttemptSequence(record, previous, entriesById) {
44
+ const previousRecord = previous?.record;
45
+ const previousResult = previousRecord ? entriesById.get(previousRecord.resultEntryId) : undefined;
46
+ const continuesSeries = previousRecord !== undefined &&
47
+ previousRecord.step === record.step &&
48
+ (previousResult === undefined || previousResult.seq >= record.seq);
49
+ const expectedAttempt = continuesSeries ? previousRecord.attempt + 1 : 1;
50
+ if (record.attempt !== expectedAttempt) {
51
+ corrupt("non_consecutive_attempt", `${record.step} attempt ${record.id} is ${record.attempt}; expected ${expectedAttempt}`);
52
+ }
53
+ if (!continuesSeries || record.step === "assistant" || previousRecord === undefined)
54
+ return;
55
+ if (record.resultEntryId !== previousRecord.resultEntryId) {
56
+ corrupt("inconsistent_step", `${record.step} attempts disagree on their result entry id`);
57
+ }
58
+ if (record.compactionReason !== previousRecord.compactionReason) {
59
+ corrupt("inconsistent_step", `${record.step} attempts disagree on their compaction reason`);
60
+ }
61
+ }
62
+ function validateAttemptResult(entriesById, record) {
63
+ switch (record.step) {
64
+ case "assistant":
65
+ validateResultEntry(entriesById, record.resultEntryId, (entry) => entry.type === "message" && entry.message.role === "assistant", "assistant result");
66
+ break;
67
+ case "compaction":
68
+ validateResultEntry(entriesById, record.resultEntryId, (entry) => entry.type === "compaction", "compaction result");
69
+ break;
70
+ case "branch_summary":
71
+ validateResultEntry(entriesById, record.resultEntryId, (entry) => entry.type === "branch_summary", "branch-summary result");
72
+ break;
73
+ }
74
+ }
75
+ function validateToolStart(record, entriesById, invocations) {
76
+ const invocation = `${record.assistantEntryId}\u0000${record.toolIndex}`;
77
+ if (invocations.has(invocation)) {
78
+ corrupt("duplicate_tool_invocation", `Tool invocation ${record.assistantEntryId}:${record.toolIndex} is duplicated`);
79
+ }
80
+ invocations.add(invocation);
81
+ const assistantEntry = entriesById.get(record.assistantEntryId);
82
+ if (!assistantEntry || assistantEntry.type !== "message" || assistantEntry.message.role !== "assistant") {
83
+ corrupt("tool_call_mismatch", `Tool start ${record.id} does not reference an assistant entry`);
84
+ }
85
+ const toolCalls = assistantEntry.message.content.filter((content) => content.type === "toolCall");
86
+ const toolCall = toolCalls[record.toolIndex];
87
+ if (!toolCall || toolCall.id !== record.toolCallId || toolCall.name !== record.toolName) {
88
+ corrupt("tool_call_mismatch", `Tool start ${record.id} does not match its assistant tool-call ordinal`);
89
+ }
90
+ validateResultEntry(entriesById, record.resultEntryId, (entry) => entry.type === "message" &&
91
+ entry.message.role === "toolResult" &&
92
+ entry.message.toolCallId === record.toolCallId &&
93
+ entry.message.toolName === record.toolName, "tool result");
94
+ }
95
+ function validateDeferredHandles(entries) {
96
+ for (const entry of entries) {
97
+ if (entry.type === "message" &&
98
+ entry.message.role === "assistant" &&
99
+ entry.message.stopReason === "deferred" &&
100
+ !entry.message.deferred) {
101
+ corrupt("invalid_deferred_handle", `Deferred assistant entry ${entry.id} does not carry a handle`);
102
+ }
103
+ }
104
+ }
105
+ function validateOperationResult(entriesById, record) {
106
+ switch (record.intent.kind) {
107
+ case "run":
108
+ for (const target of record.intent.initialMessages)
109
+ validateExactProvisionedEntry(entriesById, target);
110
+ break;
111
+ case "compaction":
112
+ validateResultEntry(entriesById, record.intent.resultEntryId, (entry) => entry.type === "compaction", "manual compaction");
113
+ break;
114
+ case "navigation":
115
+ if (record.intent.summaryEntryId) {
116
+ validateResultEntry(entriesById, record.intent.summaryEntryId, (entry) => entry.type === "branch_summary", "navigation summary");
117
+ }
118
+ break;
119
+ }
120
+ }
121
+ /** Validates a bounded lane recovery slice without reading or mutating session state. */
122
+ export function validateRecordLog(input) {
123
+ if (input.openOperations.length > 1) {
124
+ corrupt("multiple_open_operations", `Lane ${input.lane} has at least two open operations`);
125
+ }
126
+ const entriesById = new Map(input.entries.map((entry) => [entry.id, entry]));
127
+ validateDeferredHandles(entriesById.values());
128
+ const starts = new Map();
129
+ const finishedAt = new Map();
130
+ const abortedAt = new Map();
131
+ const queueEnqueues = new Map();
132
+ const latestAttempt = new Map();
133
+ const toolInvocations = new Set();
134
+ const records = [...input.records].sort((left, right) => left.seq - right.seq);
135
+ for (const record of records) {
136
+ if (record.type === "operation_started") {
137
+ starts.set(record.id, record);
138
+ validateOperationResult(entriesById, record);
139
+ continue;
140
+ }
141
+ if (hasRunId(record)) {
142
+ if (!starts.has(record.runId)) {
143
+ corrupt("unknown_operation", `Record ${record.id} references unknown operation ${record.runId}`);
144
+ }
145
+ const finishSeq = finishedAt.get(record.runId);
146
+ if (finishSeq !== undefined && record.seq > finishSeq) {
147
+ corrupt("record_after_finish", `Record ${record.id} follows the finish of operation ${record.runId}`);
148
+ }
149
+ }
150
+ switch (record.type) {
151
+ case "operation_finished":
152
+ finishedAt.set(record.runId, record.seq);
153
+ break;
154
+ case "abort_requested":
155
+ abortedAt.set(record.runId, record.seq);
156
+ break;
157
+ case "step_attempt":
158
+ validateAttemptReason(record);
159
+ validateAttemptSequence(record, latestAttempt.get(record.runId), entriesById);
160
+ validateAttemptResult(entriesById, record);
161
+ latestAttempt.set(record.runId, { record });
162
+ break;
163
+ case "tool_started":
164
+ validateToolStart(record, entriesById, toolInvocations);
165
+ break;
166
+ case "queue_enqueued":
167
+ if (record.queue !== "nextRun" &&
168
+ abortedAt.get(record.runId) !== undefined &&
169
+ record.seq > abortedAt.get(record.runId)) {
170
+ corrupt("queue_after_abort", `${record.queue} item ${record.target.id} was enqueued after abort`);
171
+ }
172
+ queueEnqueues.set(record.target.id, record);
173
+ validateExactProvisionedEntry(entriesById, record.target);
174
+ break;
175
+ case "queue_cancelled": {
176
+ const enqueue = queueEnqueues.get(record.entryId);
177
+ if (!enqueue ||
178
+ enqueue.seq >= record.seq ||
179
+ enqueue.runId !== record.runId ||
180
+ entriesById.has(record.entryId)) {
181
+ corrupt("invalid_queue_cancellation", `Queue cancellation ${record.id} has no pending matching enqueue`);
182
+ }
183
+ break;
184
+ }
185
+ case "write_deferred":
186
+ validateExactProvisionedEntry(entriesById, record.target);
187
+ break;
188
+ case "usage":
189
+ break;
190
+ }
191
+ }
192
+ }
193
+ function clone(value) {
194
+ return structuredClone(value);
195
+ }
196
+ function bySequence(values) {
197
+ return [...values].sort((left, right) => left.seq - right.seq);
198
+ }
199
+ function deriveEffectiveConfiguration(input) {
200
+ let configuration = clone(input.defaults);
201
+ const entriesById = new Map();
202
+ for (const entry of [...input.configurationEntries, ...input.ownEntries])
203
+ entriesById.set(entry.id, entry);
204
+ for (const entry of bySequence([...entriesById.values()])) {
205
+ switch (entry.type) {
206
+ case "model_change":
207
+ configuration = { ...configuration, model: { provider: entry.provider, modelId: entry.modelId } };
208
+ break;
209
+ case "thinking_level_change":
210
+ configuration = { ...configuration, thinkingLevel: entry.thinkingLevel };
211
+ break;
212
+ case "active_tools_change":
213
+ configuration = { ...configuration, activeToolNames: [...entry.activeToolNames] };
214
+ break;
215
+ case "message":
216
+ if (entry.message.role === "assistant") {
217
+ configuration = {
218
+ ...configuration,
219
+ model: { provider: entry.message.provider, modelId: entry.message.model },
220
+ };
221
+ }
222
+ break;
223
+ }
224
+ }
225
+ return configuration;
226
+ }
227
+ function deriveNewestOwn(entry) {
228
+ if (!entry)
229
+ return null;
230
+ if (entry.type !== "message")
231
+ return { entryId: entry.id, type: entry.type };
232
+ if (entry.message.role !== "assistant") {
233
+ return { entryId: entry.id, type: entry.type, role: entry.message.role };
234
+ }
235
+ return {
236
+ entryId: entry.id,
237
+ type: entry.type,
238
+ role: entry.message.role,
239
+ stopReason: entry.message.stopReason,
240
+ };
241
+ }
242
+ function deriveToolBatch(operationId, records, ownEntries, entriesById, deferredWriteIds) {
243
+ const assistantEntry = [...ownEntries]
244
+ .reverse()
245
+ .find((entry) => entry.type === "message" &&
246
+ entry.message.role === "assistant" &&
247
+ entry.message.content.some((content) => content.type === "toolCall"));
248
+ if (!assistantEntry || assistantEntry.type !== "message" || assistantEntry.message.role !== "assistant")
249
+ return null;
250
+ const toolCalls = assistantEntry.message.content.filter((content) => content.type === "toolCall");
251
+ const starts = new Map();
252
+ for (const record of records) {
253
+ if (record.type === "tool_started" &&
254
+ record.runId === operationId &&
255
+ record.assistantEntryId === assistantEntry.id) {
256
+ starts.set(record.toolIndex, record);
257
+ }
258
+ }
259
+ const calls = toolCalls.map((toolCall, toolIndex) => {
260
+ const started = starts.get(toolIndex);
261
+ const startedResult = started ? entriesById.get(started.resultEntryId) : undefined;
262
+ const blockedResult = ownEntries.find((entry) => entry.seq > assistantEntry.seq &&
263
+ !deferredWriteIds.has(entry.id) &&
264
+ entry.type === "message" &&
265
+ entry.message.role === "toolResult" &&
266
+ entry.message.toolCallId === toolCall.id);
267
+ const result = startedResult ?? blockedResult;
268
+ return {
269
+ toolIndex,
270
+ toolCall: clone(toolCall),
271
+ ...(started ? { started: clone(started) } : {}),
272
+ resultExists: result !== undefined,
273
+ ...(result?.type === "message" && result.terminate === true ? { terminate: true } : {}),
274
+ };
275
+ });
276
+ return {
277
+ assistantEntryId: assistantEntry.id,
278
+ calls,
279
+ truncated: assistantEntry.message.stopReason === "length",
280
+ unresolved: calls.some((call) => !call.resultExists),
281
+ };
282
+ }
283
+ /** Purely reconstructs one lane's orchestration state from its bounded recovery inputs. */
284
+ export function reduceLaneState(input) {
285
+ validateRecordLog(input);
286
+ const records = bySequence(input.records);
287
+ const ownEntries = bySequence(input.ownEntries);
288
+ const entriesById = new Map();
289
+ for (const entry of [...input.entries, ...ownEntries])
290
+ entriesById.set(entry.id, entry);
291
+ const cancelledQueueIds = new Set(records.filter((record) => record.type === "queue_cancelled").map((record) => record.entryId));
292
+ const pendingQueueRecords = records.filter((record) => record.type === "queue_enqueued" &&
293
+ !entriesById.has(record.target.id) &&
294
+ !cancelledQueueIds.has(record.target.id));
295
+ const started = input.openOperations[0];
296
+ const capturedInitialMessageIds = new Set(started?.intent.kind === "run" ? started.intent.initialMessages.map((target) => target.id) : []);
297
+ const pendingNextRun = pendingQueueRecords
298
+ .filter((record) => record.queue === "nextRun" && !capturedInitialMessageIds.has(record.target.id))
299
+ .map((record) => clone(record.target));
300
+ const effectiveConfiguration = deriveEffectiveConfiguration(input);
301
+ if (!started) {
302
+ return {
303
+ laneState: { lane: input.lane, leafId: input.leafId, operation: null, pendingNextRun },
304
+ effectiveConfiguration,
305
+ terminalFailure: null,
306
+ };
307
+ }
308
+ const operationRecords = records.filter((record) => record.type === "operation_started" ? record.id === started.id : "runId" in record && record.runId === started.id);
309
+ const aborting = operationRecords.some((record) => record.type === "abort_requested");
310
+ const pendingSteer = aborting
311
+ ? []
312
+ : pendingQueueRecords
313
+ .filter((record) => record.queue === "steer" && record.runId === started.id)
314
+ .map((record) => clone(record.target));
315
+ const pendingFollowUp = aborting
316
+ ? []
317
+ : pendingQueueRecords
318
+ .filter((record) => record.queue === "followUp" && record.runId === started.id)
319
+ .map((record) => clone(record.target));
320
+ const pendingWrites = operationRecords
321
+ .filter((record) => record.type === "write_deferred" && !entriesById.has(record.target.id))
322
+ .map((record) => clone(record.target));
323
+ const missingInitialMessages = started.intent.kind === "run"
324
+ ? started.intent.initialMessages.filter((target) => !entriesById.has(target.id)).map(clone)
325
+ : [];
326
+ const newestAttempt = operationRecords.filter((record) => record.type === "step_attempt").at(-1);
327
+ const step = newestAttempt && !entriesById.has(newestAttempt.resultEntryId)
328
+ ? {
329
+ kind: newestAttempt.step,
330
+ attempts: newestAttempt.attempt,
331
+ resultEntryId: newestAttempt.resultEntryId,
332
+ ...(newestAttempt.step === "compaction" ? { compactionReason: newestAttempt.compactionReason } : {}),
333
+ }
334
+ : null;
335
+ const consumedInputIds = new Set();
336
+ if (started.intent.kind === "run") {
337
+ for (const target of started.intent.initialMessages)
338
+ consumedInputIds.add(target.id);
339
+ }
340
+ for (const record of operationRecords) {
341
+ if (record.type === "queue_enqueued" && record.queue !== "nextRun")
342
+ consumedInputIds.add(record.target.id);
343
+ }
344
+ let newestConsumedInputSequence = Number.NEGATIVE_INFINITY;
345
+ for (const id of consumedInputIds) {
346
+ const entry = entriesById.get(id);
347
+ if (entry?.type === "message")
348
+ newestConsumedInputSequence = Math.max(newestConsumedInputSequence, entry.seq);
349
+ }
350
+ const overflowRecoveryUsed = operationRecords.some((record) => record.type === "step_attempt" &&
351
+ record.step === "compaction" &&
352
+ record.compactionReason === "overflow" &&
353
+ record.seq > newestConsumedInputSequence);
354
+ const newestOwnEntry = ownEntries.at(-1);
355
+ const newestOwn = deriveNewestOwn(newestOwnEntry);
356
+ const deferred = newestOwnEntry?.type === "message" &&
357
+ newestOwnEntry.message.role === "assistant" &&
358
+ newestOwnEntry.message.stopReason === "deferred" &&
359
+ newestOwnEntry.message.deferred
360
+ ? clone(newestOwnEntry.message.deferred)
361
+ : null;
362
+ const targets = {};
363
+ if (started.intent.kind === "compaction") {
364
+ targets.result = entriesById.has(started.intent.resultEntryId);
365
+ }
366
+ else if (started.intent.kind === "navigation" && started.intent.summaryEntryId) {
367
+ targets.summary = entriesById.has(started.intent.summaryEntryId);
368
+ }
369
+ const deferredWriteIds = new Set(operationRecords.filter((record) => record.type === "write_deferred").map((record) => record.target.id));
370
+ let terminalFailure = null;
371
+ if (newestOwnEntry?.type === "message" &&
372
+ newestOwnEntry.message.role === "assistant" &&
373
+ newestOwnEntry.message.stopReason === "error" &&
374
+ !deferredWriteIds.has(newestOwnEntry.id)) {
375
+ const producedByStep = operationRecords.some((record) => record.type === "step_attempt" && record.resultEntryId === newestOwnEntry.id);
376
+ const previousOwnEntry = ownEntries.at(-2);
377
+ const producedByDeferredFetch = operationRecords.some((record) => record.type === "usage" && record.cause === "deferred_fetch" && record.entryId === newestOwnEntry.id) ||
378
+ (previousOwnEntry?.type === "message" &&
379
+ previousOwnEntry.message.role === "assistant" &&
380
+ previousOwnEntry.message.stopReason === "deferred");
381
+ if (producedByStep || producedByDeferredFetch) {
382
+ terminalFailure = {
383
+ entryId: newestOwnEntry.id,
384
+ source: producedByStep ? "step" : "deferred_fetch",
385
+ message: clone(newestOwnEntry.message),
386
+ };
387
+ }
388
+ }
389
+ return {
390
+ laneState: {
391
+ lane: input.lane,
392
+ leafId: input.leafId,
393
+ operation: {
394
+ id: started.id,
395
+ kind: started.intent.kind,
396
+ intent: clone(started.intent),
397
+ aborting,
398
+ step,
399
+ toolBatch: deriveToolBatch(started.id, operationRecords, ownEntries, entriesById, deferredWriteIds),
400
+ missingInitialMessages,
401
+ pendingSteer,
402
+ pendingFollowUp,
403
+ pendingWrites,
404
+ deferred,
405
+ overflowRecoveryUsed,
406
+ newestOwn,
407
+ targets,
408
+ },
409
+ pendingNextRun,
410
+ },
411
+ effectiveConfiguration,
412
+ terminalFailure,
413
+ };
414
+ }
415
+ //# sourceMappingURL=reducer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reducer.js","sourceRoot":"","sources":["../../src/harness/reducer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAkCtC,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IACpC,MAAM,CAA4B;IAE3C,YAAY,MAAiC,EAAE,OAAe,EAAE;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI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AE,IAAI,KAAK,SAAS;gBACpC,gBAAgB,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW;gBAC7C,gBAAgB,CAAC,OAAO,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;QACtD,IAAI,cAAc,IAAI,uBAAuB,EAAE,CAAC;YAC/C,eAAe,GAAG;gBACjB,OAAO,EAAE,cAAc,CAAC,EAAE;gBAC1B,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,gBAAgB;gBAClD,OAAO,EAAE,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC;aACtC,CAAC;QACH,CAAC;IACF,CAAC;IAED,OAAO;QACN,SAAS,EAAE;YACV,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,SAAS,EAAE;gBACV,EAAE,EAAE,OAAO,CAAC,EAAE;gBACd,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI;gBACzB,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;gBAC7B,QAAQ;gBACR,IAAI;gBACJ,SAAS,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,gBAAgB,CAAC;gBACnG,sBAAsB;gBACtB,YAAY;gBACZ,eAAe;gBACf,aAAa;gBACb,QAAQ;gBACR,oBAAoB;gBACpB,SAAS;gBACT,OAAO;aACP;YACD,cAAc;SACd;QACD,sBAAsB;QACtB,eAAe;KACf,CAAC;AAAA,CACF","sourcesContent":["import type { AssistantMessage, DeferredHandle, StopReason } from \"@earendil-works/pi-ai\";\nimport { Guard } from \"typebox/guard\";\nimport type { AgentMessage, AgentToolCall, ThinkingLevel } from \"../types.ts\";\nimport type {\n\tEntry,\n\tLaneRecord,\n\tOperationStartedRecord,\n\tProvisionedEntry,\n\tQueueEnqueuedRecord,\n\tStepAttemptRecord,\n\tToolStartedRecord,\n\tWriteDeferredRecord,\n} from \"./session/types.ts\";\n\n/**\n * Machine-readable category for a contradiction in a lane's durable recovery\n * slice. These indicate states the single-writer record protocol cannot\n * produce, not ordinary operation failures or incomplete-but-recoverable\n * intent/result prefixes. Restore must reject such states rather than repair or\n * continue it; the accompanying error message supplies human-readable detail.\n */\nexport type RecordLogCorruptionReason =\n\t| \"multiple_open_operations\"\n\t| \"unknown_operation\"\n\t| \"record_after_finish\"\n\t| \"non_consecutive_attempt\"\n\t| \"invalid_compaction_reason\"\n\t| \"queue_after_abort\"\n\t| \"invalid_queue_cancellation\"\n\t| \"inconsistent_step\"\n\t| \"tool_call_mismatch\"\n\t| \"duplicate_tool_invocation\"\n\t| \"provisioned_entry_mismatch\"\n\t| \"invalid_deferred_handle\";\n\nexport class RecordLogCorruption extends Error {\n\treadonly reason: RecordLogCorruptionReason;\n\n\tconstructor(reason: RecordLogCorruptionReason, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"RecordLogCorruption\";\n\t\tthis.reason = reason;\n\t}\n}\n\nexport interface RecordLogSlice {\n\tlane: string;\n\topenOperations: readonly OperationStartedRecord[];\n\trecords: readonly LaneRecord[];\n\t/** Operation-owned entries plus entries fetched directly by provisioned or referenced ids. */\n\tentries: readonly Entry[];\n}\n\nexport interface EffectiveLaneConfiguration {\n\tmodel: { provider: string; modelId: string };\n\tthinkingLevel: ThinkingLevel;\n\tactiveToolNames: string[];\n}\n\nexport interface TerminalFailureState {\n\tentryId: string;\n\tsource: \"step\" | \"deferred_fetch\";\n\tmessage: AssistantMessage;\n}\n\nexport interface ToolBatchState {\n\tassistantEntryId: string;\n\tcalls: {\n\t\ttoolIndex: number;\n\t\ttoolCall: AgentToolCall;\n\t\tstarted?: ToolStartedRecord;\n\t\tresultExists: boolean;\n\t\tterminate?: boolean;\n\t}[];\n\ttruncated: boolean;\n\tunresolved: boolean;\n}\n\nexport interface LaneState {\n\tlane: string;\n\tleafId: string | null;\n\toperation: null | {\n\t\tid: string;\n\t\tkind: \"run\" | \"compaction\" | \"navigation\";\n\t\tintent: OperationStartedRecord[\"intent\"];\n\t\taborting: boolean;\n\t\tstep: null | {\n\t\t\tkind: \"assistant\" | \"compaction\" | \"branch_summary\";\n\t\t\tattempts: number;\n\t\t\tresultEntryId: string;\n\t\t\tcompactionReason?: \"manual\" | \"threshold\" | \"overflow\";\n\t\t};\n\t\ttoolBatch: ToolBatchState | null;\n\t\tmissingInitialMessages: ProvisionedEntry[];\n\t\tpendingSteer: ProvisionedEntry[];\n\t\tpendingFollowUp: ProvisionedEntry[];\n\t\tpendingWrites: ProvisionedEntry[];\n\t\tdeferred: DeferredHandle | null;\n\t\toverflowRecoveryUsed: boolean;\n\t\tnewestOwn: null | {\n\t\t\tentryId: string;\n\t\t\ttype: Entry[\"type\"];\n\t\t\trole?: AgentMessage[\"role\"];\n\t\t\tstopReason?: StopReason;\n\t\t};\n\t\ttargets: { result?: boolean; summary?: boolean };\n\t};\n\tpendingNextRun: ProvisionedEntry[];\n}\n\nexport interface LaneReductionInput extends RecordLogSlice {\n\tleafId: string | null;\n\t/** Entries appended by the open operation, oldest first. Empty when idle. */\n\townEntries: readonly Entry[];\n\t/** Bounded effective-state lookups at the operation anchor or idle leaf, oldest first. */\n\tconfigurationEntries: readonly Entry[];\n\t/** Harness option fallbacks used when no persisted value exists. */\n\tdefaults: EffectiveLaneConfiguration;\n}\n\nexport interface LaneReductionResult {\n\tlaneState: LaneState;\n\teffectiveConfiguration: EffectiveLaneConfiguration;\n\tterminalFailure: TerminalFailureState | null;\n}\n\ninterface AttemptSeries {\n\trecord: StepAttemptRecord;\n}\n\nfunction corrupt(reason: RecordLogCorruptionReason, message: string): never {\n\tthrow new RecordLogCorruption(reason, message);\n}\n\nfunction hasRunId(record: LaneRecord): record is Exclude<LaneRecord, OperationStartedRecord> & { runId: string } {\n\treturn \"runId\" in record && typeof record.runId === \"string\";\n}\n\nfunction matchesProvisionedEntry(entry: Entry, target: ProvisionedEntry): boolean {\n\tconst { parentId: _parentId, seq: _seq, timestamp: _timestamp, ...payload } = entry;\n\treturn Guard.IsDeepEqual(payload, target);\n}\n\nfunction validateExactProvisionedEntry(entriesById: ReadonlyMap<string, Entry>, target: ProvisionedEntry): void {\n\tconst entry = entriesById.get(target.id);\n\tif (entry && !matchesProvisionedEntry(entry, target)) {\n\t\tcorrupt(\n\t\t\t\"provisioned_entry_mismatch\",\n\t\t\t`Provisioned entry ${target.id} exists with content different from its intent`,\n\t\t);\n\t}\n}\n\nfunction validateResultEntry(\n\tentriesById: ReadonlyMap<string, Entry>,\n\tresultEntryId: string,\n\tmatches: (entry: Entry) => boolean,\n\tdescription: string,\n): void {\n\tconst entry = entriesById.get(resultEntryId);\n\tif (entry && !matches(entry)) {\n\t\tcorrupt(\n\t\t\t\"provisioned_entry_mismatch\",\n\t\t\t`Provisioned ${description} entry ${resultEntryId} exists with different content`,\n\t\t);\n\t}\n}\n\nfunction validateAttemptReason(record: StepAttemptRecord): void {\n\tconst reason = (record as { compactionReason?: unknown }).compactionReason;\n\tif (record.step === \"compaction\") {\n\t\tif (reason !== \"manual\" && reason !== \"threshold\" && reason !== \"overflow\") {\n\t\t\tcorrupt(\"invalid_compaction_reason\", `Compaction attempt ${record.id} has no valid compaction reason`);\n\t\t}\n\t} else if (reason !== undefined) {\n\t\tcorrupt(\"invalid_compaction_reason\", `${record.step} attempt ${record.id} has a compaction reason`);\n\t}\n}\n\nfunction validateAttemptSequence(\n\trecord: StepAttemptRecord,\n\tprevious: AttemptSeries | undefined,\n\tentriesById: ReadonlyMap<string, Entry>,\n): void {\n\tconst previousRecord = previous?.record;\n\tconst previousResult = previousRecord ? entriesById.get(previousRecord.resultEntryId) : undefined;\n\tconst continuesSeries =\n\t\tpreviousRecord !== undefined &&\n\t\tpreviousRecord.step === record.step &&\n\t\t(previousResult === undefined || previousResult.seq >= record.seq);\n\tconst expectedAttempt = continuesSeries ? previousRecord.attempt + 1 : 1;\n\tif (record.attempt !== expectedAttempt) {\n\t\tcorrupt(\n\t\t\t\"non_consecutive_attempt\",\n\t\t\t`${record.step} attempt ${record.id} is ${record.attempt}; expected ${expectedAttempt}`,\n\t\t);\n\t}\n\tif (!continuesSeries || record.step === \"assistant\" || previousRecord === undefined) return;\n\tif (record.resultEntryId !== previousRecord.resultEntryId) {\n\t\tcorrupt(\"inconsistent_step\", `${record.step} attempts disagree on their result entry id`);\n\t}\n\tif (record.compactionReason !== previousRecord.compactionReason) {\n\t\tcorrupt(\"inconsistent_step\", `${record.step} attempts disagree on their compaction reason`);\n\t}\n}\n\nfunction validateAttemptResult(entriesById: ReadonlyMap<string, Entry>, record: StepAttemptRecord): void {\n\tswitch (record.step) {\n\t\tcase \"assistant\":\n\t\t\tvalidateResultEntry(\n\t\t\t\tentriesById,\n\t\t\t\trecord.resultEntryId,\n\t\t\t\t(entry) => entry.type === \"message\" && entry.message.role === \"assistant\",\n\t\t\t\t\"assistant result\",\n\t\t\t);\n\t\t\tbreak;\n\t\tcase \"compaction\":\n\t\t\tvalidateResultEntry(\n\t\t\t\tentriesById,\n\t\t\t\trecord.resultEntryId,\n\t\t\t\t(entry) => entry.type === \"compaction\",\n\t\t\t\t\"compaction result\",\n\t\t\t);\n\t\t\tbreak;\n\t\tcase \"branch_summary\":\n\t\t\tvalidateResultEntry(\n\t\t\t\tentriesById,\n\t\t\t\trecord.resultEntryId,\n\t\t\t\t(entry) => entry.type === \"branch_summary\",\n\t\t\t\t\"branch-summary result\",\n\t\t\t);\n\t\t\tbreak;\n\t}\n}\n\nfunction validateToolStart(\n\trecord: Extract<LaneRecord, { type: \"tool_started\" }>,\n\tentriesById: ReadonlyMap<string, Entry>,\n\tinvocations: Set<string>,\n): void {\n\tconst invocation = `${record.assistantEntryId}\\u0000${record.toolIndex}`;\n\tif (invocations.has(invocation)) {\n\t\tcorrupt(\n\t\t\t\"duplicate_tool_invocation\",\n\t\t\t`Tool invocation ${record.assistantEntryId}:${record.toolIndex} is duplicated`,\n\t\t);\n\t}\n\tinvocations.add(invocation);\n\n\tconst assistantEntry = entriesById.get(record.assistantEntryId);\n\tif (!assistantEntry || assistantEntry.type !== \"message\" || assistantEntry.message.role !== \"assistant\") {\n\t\tcorrupt(\"tool_call_mismatch\", `Tool start ${record.id} does not reference an assistant entry`);\n\t}\n\tconst toolCalls = assistantEntry.message.content.filter((content) => content.type === \"toolCall\");\n\tconst toolCall = toolCalls[record.toolIndex];\n\tif (!toolCall || toolCall.id !== record.toolCallId || toolCall.name !== record.toolName) {\n\t\tcorrupt(\"tool_call_mismatch\", `Tool start ${record.id} does not match its assistant tool-call ordinal`);\n\t}\n\n\tvalidateResultEntry(\n\t\tentriesById,\n\t\trecord.resultEntryId,\n\t\t(entry) =>\n\t\t\tentry.type === \"message\" &&\n\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\tentry.message.toolCallId === record.toolCallId &&\n\t\t\tentry.message.toolName === record.toolName,\n\t\t\"tool result\",\n\t);\n}\n\nfunction validateDeferredHandles(entries: Iterable<Entry>): void {\n\tfor (const entry of entries) {\n\t\tif (\n\t\t\tentry.type === \"message\" &&\n\t\t\tentry.message.role === \"assistant\" &&\n\t\t\tentry.message.stopReason === \"deferred\" &&\n\t\t\t!entry.message.deferred\n\t\t) {\n\t\t\tcorrupt(\"invalid_deferred_handle\", `Deferred assistant entry ${entry.id} does not carry a handle`);\n\t\t}\n\t}\n}\n\nfunction validateOperationResult(entriesById: ReadonlyMap<string, Entry>, record: OperationStartedRecord): void {\n\tswitch (record.intent.kind) {\n\t\tcase \"run\":\n\t\t\tfor (const target of record.intent.initialMessages) validateExactProvisionedEntry(entriesById, target);\n\t\t\tbreak;\n\t\tcase \"compaction\":\n\t\t\tvalidateResultEntry(\n\t\t\t\tentriesById,\n\t\t\t\trecord.intent.resultEntryId,\n\t\t\t\t(entry) => entry.type === \"compaction\",\n\t\t\t\t\"manual compaction\",\n\t\t\t);\n\t\t\tbreak;\n\t\tcase \"navigation\":\n\t\t\tif (record.intent.summaryEntryId) {\n\t\t\t\tvalidateResultEntry(\n\t\t\t\t\tentriesById,\n\t\t\t\t\trecord.intent.summaryEntryId,\n\t\t\t\t\t(entry) => entry.type === \"branch_summary\",\n\t\t\t\t\t\"navigation summary\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\n/** Validates a bounded lane recovery slice without reading or mutating session state. */\nexport function validateRecordLog(input: RecordLogSlice): void {\n\tif (input.openOperations.length > 1) {\n\t\tcorrupt(\"multiple_open_operations\", `Lane ${input.lane} has at least two open operations`);\n\t}\n\n\tconst entriesById = new Map(input.entries.map((entry) => [entry.id, entry]));\n\tvalidateDeferredHandles(entriesById.values());\n\tconst starts = new Map<string, OperationStartedRecord>();\n\tconst finishedAt = new Map<string, number>();\n\tconst abortedAt = new Map<string, number>();\n\tconst queueEnqueues = new Map<string, Extract<LaneRecord, { type: \"queue_enqueued\" }>>();\n\tconst latestAttempt = new Map<string, AttemptSeries>();\n\tconst toolInvocations = new Set<string>();\n\tconst records = [...input.records].sort((left, right) => left.seq - right.seq);\n\n\tfor (const record of records) {\n\t\tif (record.type === \"operation_started\") {\n\t\t\tstarts.set(record.id, record);\n\t\t\tvalidateOperationResult(entriesById, record);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (hasRunId(record)) {\n\t\t\tif (!starts.has(record.runId)) {\n\t\t\t\tcorrupt(\"unknown_operation\", `Record ${record.id} references unknown operation ${record.runId}`);\n\t\t\t}\n\t\t\tconst finishSeq = finishedAt.get(record.runId);\n\t\t\tif (finishSeq !== undefined && record.seq > finishSeq) {\n\t\t\t\tcorrupt(\"record_after_finish\", `Record ${record.id} follows the finish of operation ${record.runId}`);\n\t\t\t}\n\t\t}\n\n\t\tswitch (record.type) {\n\t\t\tcase \"operation_finished\":\n\t\t\t\tfinishedAt.set(record.runId, record.seq);\n\t\t\t\tbreak;\n\t\t\tcase \"abort_requested\":\n\t\t\t\tabortedAt.set(record.runId, record.seq);\n\t\t\t\tbreak;\n\t\t\tcase \"step_attempt\":\n\t\t\t\tvalidateAttemptReason(record);\n\t\t\t\tvalidateAttemptSequence(record, latestAttempt.get(record.runId), entriesById);\n\t\t\t\tvalidateAttemptResult(entriesById, record);\n\t\t\t\tlatestAttempt.set(record.runId, { record });\n\t\t\t\tbreak;\n\t\t\tcase \"tool_started\":\n\t\t\t\tvalidateToolStart(record, entriesById, toolInvocations);\n\t\t\t\tbreak;\n\t\t\tcase \"queue_enqueued\":\n\t\t\t\tif (\n\t\t\t\t\trecord.queue !== \"nextRun\" &&\n\t\t\t\t\tabortedAt.get(record.runId) !== undefined &&\n\t\t\t\t\trecord.seq > abortedAt.get(record.runId)!\n\t\t\t\t) {\n\t\t\t\t\tcorrupt(\"queue_after_abort\", `${record.queue} item ${record.target.id} was enqueued after abort`);\n\t\t\t\t}\n\t\t\t\tqueueEnqueues.set(record.target.id, record);\n\t\t\t\tvalidateExactProvisionedEntry(entriesById, record.target);\n\t\t\t\tbreak;\n\t\t\tcase \"queue_cancelled\": {\n\t\t\t\tconst enqueue = queueEnqueues.get(record.entryId);\n\t\t\t\tif (\n\t\t\t\t\t!enqueue ||\n\t\t\t\t\tenqueue.seq >= record.seq ||\n\t\t\t\t\tenqueue.runId !== record.runId ||\n\t\t\t\t\tentriesById.has(record.entryId)\n\t\t\t\t) {\n\t\t\t\t\tcorrupt(\"invalid_queue_cancellation\", `Queue cancellation ${record.id} has no pending matching enqueue`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"write_deferred\":\n\t\t\t\tvalidateExactProvisionedEntry(entriesById, record.target);\n\t\t\t\tbreak;\n\t\t\tcase \"usage\":\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nfunction clone<T>(value: T): T {\n\treturn structuredClone(value);\n}\n\nfunction bySequence<T extends { seq: number }>(values: readonly T[]): T[] {\n\treturn [...values].sort((left, right) => left.seq - right.seq);\n}\n\nfunction deriveEffectiveConfiguration(input: LaneReductionInput): EffectiveLaneConfiguration {\n\tlet configuration = clone(input.defaults);\n\tconst entriesById = new Map<string, Entry>();\n\tfor (const entry of [...input.configurationEntries, ...input.ownEntries]) entriesById.set(entry.id, entry);\n\n\tfor (const entry of bySequence([...entriesById.values()])) {\n\t\tswitch (entry.type) {\n\t\t\tcase \"model_change\":\n\t\t\t\tconfiguration = { ...configuration, model: { provider: entry.provider, modelId: entry.modelId } };\n\t\t\t\tbreak;\n\t\t\tcase \"thinking_level_change\":\n\t\t\t\tconfiguration = { ...configuration, thinkingLevel: entry.thinkingLevel as ThinkingLevel };\n\t\t\t\tbreak;\n\t\t\tcase \"active_tools_change\":\n\t\t\t\tconfiguration = { ...configuration, activeToolNames: [...entry.activeToolNames] };\n\t\t\t\tbreak;\n\t\t\tcase \"message\":\n\t\t\t\tif (entry.message.role === \"assistant\") {\n\t\t\t\t\tconfiguration = {\n\t\t\t\t\t\t...configuration,\n\t\t\t\t\t\tmodel: { provider: entry.message.provider, modelId: entry.message.model },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn configuration;\n}\n\nfunction deriveNewestOwn(\n\tentry: Entry | undefined,\n): NonNullable<NonNullable<LaneState[\"operation\"]>[\"newestOwn\"]> | null {\n\tif (!entry) return null;\n\tif (entry.type !== \"message\") return { entryId: entry.id, type: entry.type };\n\tif (entry.message.role !== \"assistant\") {\n\t\treturn { entryId: entry.id, type: entry.type, role: entry.message.role };\n\t}\n\treturn {\n\t\tentryId: entry.id,\n\t\ttype: entry.type,\n\t\trole: entry.message.role,\n\t\tstopReason: entry.message.stopReason,\n\t};\n}\n\nfunction deriveToolBatch(\n\toperationId: string,\n\trecords: readonly LaneRecord[],\n\townEntries: readonly Entry[],\n\tentriesById: ReadonlyMap<string, Entry>,\n\tdeferredWriteIds: ReadonlySet<string>,\n): ToolBatchState | null {\n\tconst assistantEntry = [...ownEntries]\n\t\t.reverse()\n\t\t.find(\n\t\t\t(entry) =>\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\tentry.message.role === \"assistant\" &&\n\t\t\t\tentry.message.content.some((content) => content.type === \"toolCall\"),\n\t\t);\n\tif (!assistantEntry || assistantEntry.type !== \"message\" || assistantEntry.message.role !== \"assistant\") return null;\n\n\tconst toolCalls = assistantEntry.message.content.filter(\n\t\t(content): content is AgentToolCall => content.type === \"toolCall\",\n\t);\n\tconst starts = new Map<number, ToolStartedRecord>();\n\tfor (const record of records) {\n\t\tif (\n\t\t\trecord.type === \"tool_started\" &&\n\t\t\trecord.runId === operationId &&\n\t\t\trecord.assistantEntryId === assistantEntry.id\n\t\t) {\n\t\t\tstarts.set(record.toolIndex, record);\n\t\t}\n\t}\n\n\tconst calls = toolCalls.map((toolCall, toolIndex) => {\n\t\tconst started = starts.get(toolIndex);\n\t\tconst startedResult = started ? entriesById.get(started.resultEntryId) : undefined;\n\t\tconst blockedResult = ownEntries.find(\n\t\t\t(entry) =>\n\t\t\t\tentry.seq > assistantEntry.seq &&\n\t\t\t\t!deferredWriteIds.has(entry.id) &&\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\tentry.message.toolCallId === toolCall.id,\n\t\t);\n\t\tconst result = startedResult ?? blockedResult;\n\t\treturn {\n\t\t\ttoolIndex,\n\t\t\ttoolCall: clone(toolCall),\n\t\t\t...(started ? { started: clone(started) } : {}),\n\t\t\tresultExists: result !== undefined,\n\t\t\t...(result?.type === \"message\" && result.terminate === true ? { terminate: true } : {}),\n\t\t};\n\t});\n\n\treturn {\n\t\tassistantEntryId: assistantEntry.id,\n\t\tcalls,\n\t\ttruncated: assistantEntry.message.stopReason === \"length\",\n\t\tunresolved: calls.some((call) => !call.resultExists),\n\t};\n}\n\n/** Purely reconstructs one lane's orchestration state from its bounded recovery inputs. */\nexport function reduceLaneState(input: LaneReductionInput): LaneReductionResult {\n\tvalidateRecordLog(input);\n\n\tconst records = bySequence(input.records);\n\tconst ownEntries = bySequence(input.ownEntries);\n\tconst entriesById = new Map<string, Entry>();\n\tfor (const entry of [...input.entries, ...ownEntries]) entriesById.set(entry.id, entry);\n\tconst cancelledQueueIds = new Set(\n\t\trecords.filter((record) => record.type === \"queue_cancelled\").map((record) => record.entryId),\n\t);\n\tconst pendingQueueRecords = records.filter(\n\t\t(record): record is QueueEnqueuedRecord =>\n\t\t\trecord.type === \"queue_enqueued\" &&\n\t\t\t!entriesById.has(record.target.id) &&\n\t\t\t!cancelledQueueIds.has(record.target.id),\n\t);\n\tconst started = input.openOperations[0];\n\tconst capturedInitialMessageIds = new Set(\n\t\tstarted?.intent.kind === \"run\" ? started.intent.initialMessages.map((target) => target.id) : [],\n\t);\n\tconst pendingNextRun = pendingQueueRecords\n\t\t.filter((record) => record.queue === \"nextRun\" && !capturedInitialMessageIds.has(record.target.id))\n\t\t.map((record) => clone(record.target));\n\tconst effectiveConfiguration = deriveEffectiveConfiguration(input);\n\n\tif (!started) {\n\t\treturn {\n\t\t\tlaneState: { lane: input.lane, leafId: input.leafId, operation: null, pendingNextRun },\n\t\t\teffectiveConfiguration,\n\t\t\tterminalFailure: null,\n\t\t};\n\t}\n\n\tconst operationRecords = records.filter((record) =>\n\t\trecord.type === \"operation_started\" ? record.id === started.id : \"runId\" in record && record.runId === started.id,\n\t);\n\tconst aborting = operationRecords.some((record) => record.type === \"abort_requested\");\n\tconst pendingSteer = aborting\n\t\t? []\n\t\t: pendingQueueRecords\n\t\t\t\t.filter((record) => record.queue === \"steer\" && record.runId === started.id)\n\t\t\t\t.map((record) => clone(record.target));\n\tconst pendingFollowUp = aborting\n\t\t? []\n\t\t: pendingQueueRecords\n\t\t\t\t.filter((record) => record.queue === \"followUp\" && record.runId === started.id)\n\t\t\t\t.map((record) => clone(record.target));\n\tconst pendingWrites = operationRecords\n\t\t.filter(\n\t\t\t(record): record is WriteDeferredRecord =>\n\t\t\t\trecord.type === \"write_deferred\" && !entriesById.has(record.target.id),\n\t\t)\n\t\t.map((record) => clone(record.target));\n\tconst missingInitialMessages =\n\t\tstarted.intent.kind === \"run\"\n\t\t\t? started.intent.initialMessages.filter((target) => !entriesById.has(target.id)).map(clone)\n\t\t\t: [];\n\n\tconst newestAttempt = operationRecords.filter((record) => record.type === \"step_attempt\").at(-1);\n\tconst step =\n\t\tnewestAttempt && !entriesById.has(newestAttempt.resultEntryId)\n\t\t\t? {\n\t\t\t\t\tkind: newestAttempt.step,\n\t\t\t\t\tattempts: newestAttempt.attempt,\n\t\t\t\t\tresultEntryId: newestAttempt.resultEntryId,\n\t\t\t\t\t...(newestAttempt.step === \"compaction\" ? { compactionReason: newestAttempt.compactionReason } : {}),\n\t\t\t\t}\n\t\t\t: null;\n\n\tconst consumedInputIds = new Set<string>();\n\tif (started.intent.kind === \"run\") {\n\t\tfor (const target of started.intent.initialMessages) consumedInputIds.add(target.id);\n\t}\n\tfor (const record of operationRecords) {\n\t\tif (record.type === \"queue_enqueued\" && record.queue !== \"nextRun\") consumedInputIds.add(record.target.id);\n\t}\n\tlet newestConsumedInputSequence = Number.NEGATIVE_INFINITY;\n\tfor (const id of consumedInputIds) {\n\t\tconst entry = entriesById.get(id);\n\t\tif (entry?.type === \"message\") newestConsumedInputSequence = Math.max(newestConsumedInputSequence, entry.seq);\n\t}\n\tconst overflowRecoveryUsed = operationRecords.some(\n\t\t(record) =>\n\t\t\trecord.type === \"step_attempt\" &&\n\t\t\trecord.step === \"compaction\" &&\n\t\t\trecord.compactionReason === \"overflow\" &&\n\t\t\trecord.seq > newestConsumedInputSequence,\n\t);\n\n\tconst newestOwnEntry = ownEntries.at(-1);\n\tconst newestOwn = deriveNewestOwn(newestOwnEntry);\n\tconst deferred =\n\t\tnewestOwnEntry?.type === \"message\" &&\n\t\tnewestOwnEntry.message.role === \"assistant\" &&\n\t\tnewestOwnEntry.message.stopReason === \"deferred\" &&\n\t\tnewestOwnEntry.message.deferred\n\t\t\t? clone(newestOwnEntry.message.deferred)\n\t\t\t: null;\n\tconst targets: { result?: boolean; summary?: boolean } = {};\n\tif (started.intent.kind === \"compaction\") {\n\t\ttargets.result = entriesById.has(started.intent.resultEntryId);\n\t} else if (started.intent.kind === \"navigation\" && started.intent.summaryEntryId) {\n\t\ttargets.summary = entriesById.has(started.intent.summaryEntryId);\n\t}\n\n\tconst deferredWriteIds = new Set(\n\t\toperationRecords.filter((record) => record.type === \"write_deferred\").map((record) => record.target.id),\n\t);\n\tlet terminalFailure: TerminalFailureState | null = null;\n\tif (\n\t\tnewestOwnEntry?.type === \"message\" &&\n\t\tnewestOwnEntry.message.role === \"assistant\" &&\n\t\tnewestOwnEntry.message.stopReason === \"error\" &&\n\t\t!deferredWriteIds.has(newestOwnEntry.id)\n\t) {\n\t\tconst producedByStep = operationRecords.some(\n\t\t\t(record) => record.type === \"step_attempt\" && record.resultEntryId === newestOwnEntry.id,\n\t\t);\n\t\tconst previousOwnEntry = ownEntries.at(-2);\n\t\tconst producedByDeferredFetch =\n\t\t\toperationRecords.some(\n\t\t\t\t(record) =>\n\t\t\t\t\trecord.type === \"usage\" && record.cause === \"deferred_fetch\" && record.entryId === newestOwnEntry.id,\n\t\t\t) ||\n\t\t\t(previousOwnEntry?.type === \"message\" &&\n\t\t\t\tpreviousOwnEntry.message.role === \"assistant\" &&\n\t\t\t\tpreviousOwnEntry.message.stopReason === \"deferred\");\n\t\tif (producedByStep || producedByDeferredFetch) {\n\t\t\tterminalFailure = {\n\t\t\t\tentryId: newestOwnEntry.id,\n\t\t\t\tsource: producedByStep ? \"step\" : \"deferred_fetch\",\n\t\t\t\tmessage: clone(newestOwnEntry.message),\n\t\t\t};\n\t\t}\n\t}\n\n\treturn {\n\t\tlaneState: {\n\t\t\tlane: input.lane,\n\t\t\tleafId: input.leafId,\n\t\t\toperation: {\n\t\t\t\tid: started.id,\n\t\t\t\tkind: started.intent.kind,\n\t\t\t\tintent: clone(started.intent),\n\t\t\t\taborting,\n\t\t\t\tstep,\n\t\t\t\ttoolBatch: deriveToolBatch(started.id, operationRecords, ownEntries, entriesById, deferredWriteIds),\n\t\t\t\tmissingInitialMessages,\n\t\t\t\tpendingSteer,\n\t\t\t\tpendingFollowUp,\n\t\t\t\tpendingWrites,\n\t\t\t\tdeferred,\n\t\t\t\toverflowRecoveryUsed,\n\t\t\t\tnewestOwn,\n\t\t\t\ttargets,\n\t\t\t},\n\t\t\tpendingNextRun,\n\t\t},\n\t\teffectiveConfiguration,\n\t\tterminalFailure,\n\t};\n}\n"]}
@@ -0,0 +1,40 @@
1
+ export type Result<TValue, TError> = {
2
+ ok: true;
3
+ value: TValue;
4
+ } | {
5
+ ok: false;
6
+ error: TError;
7
+ };
8
+ export declare const Result: {
9
+ ok<TValue>(value: TValue): Result<TValue, never>;
10
+ err<TError>(error: TError): Result<never, TError>;
11
+ isOk<TValue, TError>(result: Result<TValue, TError>): result is {
12
+ ok: true;
13
+ value: TValue;
14
+ };
15
+ isErr<TValue, TError>(result: Result<TValue, TError>): result is {
16
+ ok: false;
17
+ error: TError;
18
+ };
19
+ };
20
+ export interface TaggedErrorValue<Tag extends string> extends Error {
21
+ readonly _tag: Tag;
22
+ toJSON(): {
23
+ _tag: Tag;
24
+ message: string;
25
+ } & Record<string, unknown>;
26
+ }
27
+ export interface TaggedErrorFactory<Tag extends string> {
28
+ new <Props extends {
29
+ message: string;
30
+ }>(props: Props): TaggedErrorValue<Tag> & Readonly<Props>;
31
+ is(value: unknown): value is TaggedErrorValue<Tag>;
32
+ }
33
+ export declare function TaggedError<Tag extends string>(tag: Tag): TaggedErrorFactory<Tag>;
34
+ export type ErrorMatchers<TError extends TaggedErrorValue<string>, TValue> = {
35
+ [Tag in TError["_tag"]]: (error: Extract<TError, {
36
+ _tag: Tag;
37
+ }>) => TValue;
38
+ };
39
+ export declare function matchError<TError extends TaggedErrorValue<string>, TValue>(error: TError, matchers: ErrorMatchers<TError, TValue>): TValue;
40
+ //# sourceMappingURL=result.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result.d.ts","sourceRoot":"","sources":["../../src/harness/result.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,MAAM,CAAC,MAAM,EAAE,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,CAAC,EAAE,MAAM,EACzE,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,GACrC,MAAM,CAGR","sourcesContent":["export type Result<TValue, TError> = { ok: true; value: TValue } | { ok: false; error: TError };\n\nexport const Result = {\n\tok<TValue>(value: TValue): Result<TValue, never> {\n\t\treturn { ok: true, value };\n\t},\n\terr<TError>(error: TError): Result<never, TError> {\n\t\treturn { ok: false, error };\n\t},\n\tisOk<TValue, TError>(result: Result<TValue, TError>): result is { ok: true; value: TValue } {\n\t\treturn result.ok;\n\t},\n\tisErr<TValue, TError>(result: Result<TValue, TError>): result is { ok: false; error: TError } {\n\t\treturn !result.ok;\n\t},\n};\n\nexport interface TaggedErrorValue<Tag extends string> extends Error {\n\treadonly _tag: Tag;\n\ttoJSON(): { _tag: Tag; message: string } & Record<string, unknown>;\n}\n\nexport interface TaggedErrorFactory<Tag extends string> {\n\tnew <Props extends { message: string }>(props: Props): TaggedErrorValue<Tag> & Readonly<Props>;\n\tis(value: unknown): value is TaggedErrorValue<Tag>;\n}\n\nexport function TaggedError<Tag extends string>(tag: Tag): TaggedErrorFactory<Tag> {\n\tclass TaggedErrorClass extends Error {\n\t\treadonly _tag = tag;\n\n\t\tconstructor(props: { message: string } & Record<string, unknown>) {\n\t\t\tsuper(props.message);\n\t\t\tthis.name = tag;\n\t\t\tObject.assign(this, props);\n\t\t}\n\n\t\ttoJSON(): { _tag: Tag; message: string } & Record<string, unknown> {\n\t\t\tconst payload: Record<string, unknown> = {};\n\t\t\tfor (const key of Object.keys(this)) {\n\t\t\t\tif (key !== \"_tag\") payload[key] = (this as unknown as Record<string, unknown>)[key];\n\t\t\t}\n\t\t\treturn { _tag: tag, message: this.message, ...payload };\n\t\t}\n\n\t\tstatic is(value: unknown): value is TaggedErrorValue<Tag> {\n\t\t\treturn value instanceof TaggedErrorClass;\n\t\t}\n\t}\n\treturn TaggedErrorClass as unknown as TaggedErrorFactory<Tag>;\n}\n\nexport type ErrorMatchers<TError extends TaggedErrorValue<string>, TValue> = {\n\t[Tag in TError[\"_tag\"]]: (error: Extract<TError, { _tag: Tag }>) => TValue;\n};\n\nexport function matchError<TError extends TaggedErrorValue<string>, TValue>(\n\terror: TError,\n\tmatchers: ErrorMatchers<TError, TValue>,\n): TValue {\n\tconst matcher = (matchers as unknown as Record<string, (value: TError) => TValue>)[error._tag];\n\treturn matcher(error);\n}\n"]}
@@ -0,0 +1,41 @@
1
+ export const Result = {
2
+ ok(value) {
3
+ return { ok: true, value };
4
+ },
5
+ err(error) {
6
+ return { ok: false, error };
7
+ },
8
+ isOk(result) {
9
+ return result.ok;
10
+ },
11
+ isErr(result) {
12
+ return !result.ok;
13
+ },
14
+ };
15
+ export function TaggedError(tag) {
16
+ class TaggedErrorClass extends Error {
17
+ _tag = tag;
18
+ constructor(props) {
19
+ super(props.message);
20
+ this.name = tag;
21
+ Object.assign(this, props);
22
+ }
23
+ toJSON() {
24
+ const payload = {};
25
+ for (const key of Object.keys(this)) {
26
+ if (key !== "_tag")
27
+ payload[key] = this[key];
28
+ }
29
+ return { _tag: tag, message: this.message, ...payload };
30
+ }
31
+ static is(value) {
32
+ return value instanceof TaggedErrorClass;
33
+ }
34
+ }
35
+ return TaggedErrorClass;
36
+ }
37
+ export function matchError(error, matchers) {
38
+ const matcher = matchers[error._tag];
39
+ return matcher(error);
40
+ }
41
+ //# sourceMappingURL=result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result.js","sourceRoot":"","sources":["../../src/harness/result.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,MAAM,GAAG;IACrB,EAAE,CAAS,KAAa,EAAyB;QAChD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAAA,CAC3B;IACD,GAAG,CAAS,KAAa,EAAyB;QACjD,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAAA,CAC5B;IACD,IAAI,CAAiB,MAA8B,EAAyC;QAC3F,OAAO,MAAM,CAAC,EAAE,CAAC;IAAA,CACjB;IACD,KAAK,CAAiB,MAA8B,EAA0C;QAC7F,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;IAAA,CAClB;CACD,CAAC;AAYF,MAAM,UAAU,WAAW,CAAqB,GAAQ,EAA2B;IAClF,MAAM,gBAAiB,SAAQ,KAAK;QAC1B,IAAI,GAAG,GAAG,CAAC;QAEpB,YAAY,KAAoD,EAAE;YACjE,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACrB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;YAChB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAAA,CAC3B;QAED,MAAM,GAA6D;YAClE,MAAM,OAAO,GAA4B,EAAE,CAAC;YAC5C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrC,IAAI,GAAG,KAAK,MAAM;oBAAE,OAAO,CAAC,GAAG,CAAC,GAAI,IAA2C,CAAC,GAAG,CAAC,CAAC;YACtF,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;QAAA,CACxD;QAED,MAAM,CAAC,EAAE,CAAC,KAAc,EAAkC;YACzD,OAAO,KAAK,YAAY,gBAAgB,CAAC;QAAA,CACzC;KACD;IACD,OAAO,gBAAsD,CAAC;AAAA,CAC9D;AAMD,MAAM,UAAU,UAAU,CACzB,KAAa,EACb,QAAuC,EAC9B;IACT,MAAM,OAAO,GAAI,QAAiE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/F,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CACtB","sourcesContent":["export type Result<TValue, TError> = { ok: true; value: TValue } | { ok: false; error: TError };\n\nexport const Result = {\n\tok<TValue>(value: TValue): Result<TValue, never> {\n\t\treturn { ok: true, value };\n\t},\n\terr<TError>(error: TError): Result<never, TError> {\n\t\treturn { ok: false, error };\n\t},\n\tisOk<TValue, TError>(result: Result<TValue, TError>): result is { ok: true; value: TValue } {\n\t\treturn result.ok;\n\t},\n\tisErr<TValue, TError>(result: Result<TValue, TError>): result is { ok: false; error: TError } {\n\t\treturn !result.ok;\n\t},\n};\n\nexport interface TaggedErrorValue<Tag extends string> extends Error {\n\treadonly _tag: Tag;\n\ttoJSON(): { _tag: Tag; message: string } & Record<string, unknown>;\n}\n\nexport interface TaggedErrorFactory<Tag extends string> {\n\tnew <Props extends { message: string }>(props: Props): TaggedErrorValue<Tag> & Readonly<Props>;\n\tis(value: unknown): value is TaggedErrorValue<Tag>;\n}\n\nexport function TaggedError<Tag extends string>(tag: Tag): TaggedErrorFactory<Tag> {\n\tclass TaggedErrorClass extends Error {\n\t\treadonly _tag = tag;\n\n\t\tconstructor(props: { message: string } & Record<string, unknown>) {\n\t\t\tsuper(props.message);\n\t\t\tthis.name = tag;\n\t\t\tObject.assign(this, props);\n\t\t}\n\n\t\ttoJSON(): { _tag: Tag; message: string } & Record<string, unknown> {\n\t\t\tconst payload: Record<string, unknown> = {};\n\t\t\tfor (const key of Object.keys(this)) {\n\t\t\t\tif (key !== \"_tag\") payload[key] = (this as unknown as Record<string, unknown>)[key];\n\t\t\t}\n\t\t\treturn { _tag: tag, message: this.message, ...payload };\n\t\t}\n\n\t\tstatic is(value: unknown): value is TaggedErrorValue<Tag> {\n\t\t\treturn value instanceof TaggedErrorClass;\n\t\t}\n\t}\n\treturn TaggedErrorClass as unknown as TaggedErrorFactory<Tag>;\n}\n\nexport type ErrorMatchers<TError extends TaggedErrorValue<string>, TValue> = {\n\t[Tag in TError[\"_tag\"]]: (error: Extract<TError, { _tag: Tag }>) => TValue;\n};\n\nexport function matchError<TError extends TaggedErrorValue<string>, TValue>(\n\terror: TError,\n\tmatchers: ErrorMatchers<TError, TValue>,\n): TValue {\n\tconst matcher = (matchers as unknown as Record<string, (value: TError) => TValue>)[error._tag];\n\treturn matcher(error);\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import type { AgentMessage } from "../../types.ts";
2
+ import type { CustomEntry, Entry } from "./types.ts";
3
+ export interface SessionContext {
4
+ messages: AgentMessage[];
5
+ thinkingLevel: string;
6
+ model: {
7
+ provider: string;
8
+ modelId: string;
9
+ } | null;
10
+ activeToolNames: string[] | null;
11
+ }
12
+ export type ContextEntryTransform = (entries: readonly Entry[]) => readonly Entry[];
13
+ export type CustomEntryContextMessageProjector = (entry: CustomEntry, index: number, entries: readonly Entry[]) => readonly AgentMessage[] | undefined;
14
+ export interface SessionContextBuildOptions {
15
+ entryTransforms?: readonly ContextEntryTransform[];
16
+ entryProjectors?: Readonly<Record<string, CustomEntryContextMessageProjector>>;
17
+ }
18
+ export declare function defaultContextEntryTransform(pathEntries: readonly Entry[]): Entry[];
19
+ export declare function buildContextEntries(pathEntries: readonly Entry[], options?: SessionContextBuildOptions): Entry[];
20
+ export declare function sessionEntryToContextMessages(entry: Entry, index: number, entries: readonly Entry[], options?: SessionContextBuildOptions): AgentMessage[];
21
+ export declare function buildSessionContext(pathEntries: readonly Entry[], options?: SessionContextBuildOptions): SessionContext;
22
+ //# sourceMappingURL=context.d.ts.map