effect-agent 0.1.0-beta.135 → 0.1.0-beta.136
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/dist/{Admin-DKqg6zQa.d.mts → Admin-Fx85KT-W.d.mts} +5 -1
- package/dist/{DurableAgentRuntime-DgzI83ng.mjs → DurableAgentRuntime-Bso5grIH.mjs} +4 -4
- package/dist/{DurableAgentRuntime-DgzI83ng.mjs.map → DurableAgentRuntime-Bso5grIH.mjs.map} +1 -1
- package/dist/{EventSource-P4hq8Opp.d.mts → EventSource-DLT8oDK8.d.mts} +2 -2
- package/dist/{PreparedInputAdmission-ChcWS1xV.d.mts → PreparedInputAdmission-CKFgG6Em.d.mts} +3 -3
- package/dist/{RunJournal-BXrq0VIK.mjs → RunJournal-Gd83HYqG.mjs} +50 -27
- package/dist/RunJournal-Gd83HYqG.mjs.map +1 -0
- package/dist/{Subscription-jOOrT8Js.d.mts → Subscription-CCmHgOYM.d.mts} +2 -2
- package/dist/{SubscriptionInput-CPyqenXR.d.mts → SubscriptionInput-BFJMhu4K.d.mts} +2 -2
- package/dist/durable/Admin.d.mts +1 -1
- package/dist/durable/AgentRegistration.d.mts +1 -1
- package/dist/durable/Certification.d.mts +1 -1
- package/dist/durable/CommittedActivity.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.mjs +1 -1
- package/dist/durable/EventSource.d.mts +1 -1
- package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
- package/dist/durable/MessageDelivery.d.mts +41 -41
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +1 -1
- package/dist/durable/PersistentHistory.d.mts +1 -1
- package/dist/durable/PersistentHistory.mjs +1 -1
- package/dist/durable/PreparedInputAdmission.d.mts +1 -1
- package/dist/durable/Recovery.d.mts +1 -1
- package/dist/durable/RunJournal.d.mts +1 -1
- package/dist/durable/RunJournal.mjs +1 -1
- package/dist/durable/Scheduling.d.mts +1 -1
- package/dist/durable/SqlStorageV2Upgrade.d.mts +1 -1
- package/dist/durable/SqlSubscriptionStore.d.mts +1 -1
- package/dist/durable/SqlThreadNativeReads.d.mts +1 -1
- package/dist/durable/SqlThreadNativeReads.mjs +1 -1
- package/dist/durable/SubmissionLedger.d.mts +1 -1
- package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
- package/dist/durable/SubmissionLedgerConformance.mjs +1 -1
- package/dist/durable/SubmissionStatus.d.mts +1 -1
- package/dist/durable/Subscription.d.mts +1 -1
- package/dist/durable/SubscriptionInput.d.mts +1 -1
- package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
- package/dist/durable/SubscriptionTools.d.mts +2 -2
- package/dist/durable/SubscriptionTransition.d.mts +1 -1
- package/dist/durable/Subscriptions.d.mts +5 -5
- package/dist/durable/ThreadContextHistory.d.mts +1 -1
- package/dist/durable/ThreadInvariants.d.mts +1 -1
- package/dist/durable/ThreadInvariants.mjs +1 -1
- package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
- package/dist/durable/ThreadStore.d.mts +1 -1
- package/dist/durable/ThreadStore.mjs +1 -1
- package/dist/durable/ThreadStoreConformance.d.mts +1 -1
- package/dist/durable/ThreadStoreConformance.mjs +1 -1
- package/dist/durable/WorkerHost.d.mts +1 -1
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
- package/src/durable/RunJournal.ts +120 -56
- package/src/durable/internal/journal-checkpoint.ts +1 -1
- package/src/durable/internal/journal-metadata.ts +10 -3
- package/dist/RunJournal-BXrq0VIK.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { O as PersistedJson } from "./Records-B5GFWCpn.mjs";
|
|
2
|
-
import { E as SubscriptionSourceError, b as SubscriptionRecord, i as EventSourceVersion, t as AcceptedEvent } from "./Subscription-
|
|
2
|
+
import { E as SubscriptionSourceError, b as SubscriptionRecord, i as EventSourceVersion, t as AcceptedEvent } from "./Subscription-CCmHgOYM.mjs";
|
|
3
3
|
import { Context, Effect, Schema, Scope } from "effect";
|
|
4
4
|
declare namespace EventSource_d_exports {
|
|
5
5
|
export { EventSource, EventSources, NormalizedEvent, makeEventSource };
|
|
@@ -48,4 +48,4 @@ declare const makeEventSource: <Event extends Schema.Top, Parameters extends Sch
|
|
|
48
48
|
}) => Effect.Effect<EventSource, never, Exclude<R, Scope.Scope> | Exclude<Event["DecodingServices"], Scope.Scope> | Exclude<Event["EncodingServices"], Scope.Scope> | Exclude<Parameters["DecodingServices"], Scope.Scope> | Exclude<Parameters["EncodingServices"], Scope.Scope>>;
|
|
49
49
|
//#endregion
|
|
50
50
|
export { makeEventSource as a, NormalizedEvent as i, EventSource_d_exports as n, EventSources as r, EventSource as t };
|
|
51
|
-
//# sourceMappingURL=EventSource-
|
|
51
|
+
//# sourceMappingURL=EventSource-DLT8oDK8.d.mts.map
|
package/dist/{PreparedInputAdmission-ChcWS1xV.d.mts → PreparedInputAdmission-CKFgG6Em.d.mts}
RENAMED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { a as Receipt } from "./Receipt-BAHyigAF.mjs";
|
|
2
2
|
import { a as FailureDiagnostic_d_exports, r as Diagnostic } from "./FailureDiagnostic-CaAkzGHL.mjs";
|
|
3
|
-
import { gi as SubmissionStatus } from "./Admin-
|
|
3
|
+
import { gi as SubmissionStatus } from "./Admin-Fx85KT-W.mjs";
|
|
4
4
|
import { H as ScheduledInputRefused, V as ScheduledInputFailure, j as ScheduleStorageError } from "./Schedule-CtYREFnz.mjs";
|
|
5
|
-
import { a as PreparedInput } from "./Subscription-
|
|
5
|
+
import { a as PreparedInput } from "./Subscription-CCmHgOYM.mjs";
|
|
6
6
|
import { Context, Effect } from "effect";
|
|
7
7
|
declare namespace PreparedInputAdmission_d_exports {
|
|
8
8
|
export { PreparedInputAdmission, admitPreparedInput };
|
|
@@ -39,4 +39,4 @@ declare const admitPreparedInput: <R>(submit: Effect.Effect<Receipt, ScheduledIn
|
|
|
39
39
|
}, ScheduleStorageError, R>;
|
|
40
40
|
//#endregion
|
|
41
41
|
export { PreparedInputAdmission_d_exports as n, admitPreparedInput as r, PreparedInputAdmission as t };
|
|
42
|
-
//# sourceMappingURL=PreparedInputAdmission-
|
|
42
|
+
//# sourceMappingURL=PreparedInputAdmission-CKFgG6Em.d.mts.map
|
|
@@ -53,7 +53,8 @@ const makeJournalMetadata = (ownerRunId, seed) => {
|
|
|
53
53
|
const from = lastResponseSequenceByRun.get(payload.runId);
|
|
54
54
|
if (from !== void 0 && from < envelope.sequence) settledSpans.push({
|
|
55
55
|
from,
|
|
56
|
-
to: envelope.sequence
|
|
56
|
+
to: envelope.sequence,
|
|
57
|
+
runId: payload.runId
|
|
57
58
|
});
|
|
58
59
|
}
|
|
59
60
|
},
|
|
@@ -397,7 +398,16 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
397
398
|
yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)));
|
|
398
399
|
metadata = collected.snapshot();
|
|
399
400
|
}
|
|
400
|
-
const { firstSequenceByRun, lastResponseSequenceByRun, terminalSequenceByRun, settledSpans, toolExecutionEvidence, settledToolCallRecordIds, settledById
|
|
401
|
+
const { firstSequenceByRun, lastResponseSequenceByRun, terminalSequenceByRun, settledSpans, toolExecutionEvidence, settledToolCallRecordIds, settledById } = metadata;
|
|
402
|
+
const declarationByResultSequence = new Map(settledSpans.map(({ from, to }) => [to, from]));
|
|
403
|
+
const isInRunView = (sequence, payload, runId) => {
|
|
404
|
+
if (runId === void 0 || payload.runId === void 0 || payload.runId === runId) return true;
|
|
405
|
+
const first = firstSequenceByRun.get(runId) ?? Number.POSITIVE_INFINITY;
|
|
406
|
+
return sequence < first || payload._tag === "ToolCallSettled" && (declarationByResultSequence.get(sequence) ?? Number.POSITIVE_INFINITY) < first;
|
|
407
|
+
};
|
|
408
|
+
const compactions = metadata.compactions.filter(({ sequence, payload }) => isInRunView(sequence, payload, ownerRunId));
|
|
409
|
+
const recordsForRun = records.pipe(Stream.filter(({ sequence, record: { payload } }) => isInRunView(sequence, payload, ownerRunId)));
|
|
410
|
+
const isCovered = (envelope, compaction) => envelope.sequence <= compaction.coversThrough && isInRunView(envelope.sequence, envelope.record.payload, compaction.runId);
|
|
401
411
|
const settledCoverage = compactions.reduce((through, { payload }) => payload.kind !== "summarize" ? Math.max(through, payload.coversThrough) : through, 0);
|
|
402
412
|
const isTerminalPriorRun = (candidateRunId, compactionRunId, beforeSequence) => {
|
|
403
413
|
const terminal = terminalSequenceByRun.get(candidateRunId);
|
|
@@ -406,7 +416,7 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
406
416
|
const incompleteResponseSequences = [];
|
|
407
417
|
let ownerPrefixSequence = seed?.firstSequence ?? Number.POSITIVE_INFINITY;
|
|
408
418
|
let protectedContext = seed?.protectedContext === void 0 ? void 0 : yield* decodePromptMessages(seed.protectedContext);
|
|
409
|
-
if (settledCoverage > 0) yield* Stream.runForEach(
|
|
419
|
+
if (settledCoverage > 0) yield* Stream.runForEach(recordsForRun, (envelope) => Effect.gen(function* () {
|
|
410
420
|
const payload = envelope.record.payload;
|
|
411
421
|
if (payload._tag !== "ModelResponseRecorded" || envelope.sequence > settledCoverage) return;
|
|
412
422
|
const messages = yield* decodePromptMessages(payload.messages);
|
|
@@ -432,14 +442,22 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
432
442
|
if (seed !== void 0 && ownSequence === seed.compaction.sequence) return seed.compaction.record.payload._tag === "CompactionCreated" && Schema.toEquivalence(CompactionCreated)(payload, seed.compaction.record.payload);
|
|
433
443
|
const ownerFirst = firstSequenceByRun.get(runId);
|
|
434
444
|
if (payload.kind === "summarize" && ownerFirst !== void 0 && coversThrough >= ownerFirst) return false;
|
|
435
|
-
if (payload.kind !== "summarize" && incompleteResponseSequences.some((response) => response.sequence <= coversThrough &&
|
|
436
|
-
|
|
445
|
+
if (payload.kind !== "summarize" && incompleteResponseSequences.some((response) => response.sequence <= coversThrough && isInRunView(response.sequence, {
|
|
446
|
+
_tag: "ModelResponseRecorded",
|
|
447
|
+
runId: response.runId
|
|
448
|
+
}, runId) && !isTerminalPriorRun(response.runId, runId, ownSequence))) return false;
|
|
449
|
+
for (const span of settledSpans) if (span.from <= coversThrough && coversThrough < span.to && isInRunView(span.from, {
|
|
450
|
+
_tag: "ModelResponseRecorded",
|
|
451
|
+
runId: span.runId
|
|
452
|
+
}, runId)) return false;
|
|
437
453
|
return true;
|
|
438
454
|
};
|
|
439
|
-
let
|
|
440
|
-
let
|
|
441
|
-
|
|
442
|
-
|
|
455
|
+
let replacements = [];
|
|
456
|
+
let clearings = [];
|
|
457
|
+
const retainCompaction = (views, next) => {
|
|
458
|
+
if (views.some((prior) => prior.payload.coversThrough > next.payload.coversThrough && isInRunView(next.sequence, next.payload, prior.payload.runId))) return views;
|
|
459
|
+
return [...views.filter((prior) => next.payload.coversThrough < prior.payload.coversThrough || !isInRunView(prior.sequence, prior.payload, next.payload.runId)), next];
|
|
460
|
+
};
|
|
443
461
|
let latestWindowId = seed?.contextWindowId;
|
|
444
462
|
let latestWindowSequence = seed?.throughSequence ?? -1;
|
|
445
463
|
let rolloverCoveredThrough = 0;
|
|
@@ -452,26 +470,31 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
452
470
|
if (payload.kind === "rollover") rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough);
|
|
453
471
|
if (payload.kind === "summarize" || payload.kind === "rollover") {
|
|
454
472
|
if (payload.kind === "summarize" && payload.summary === void 0) continue;
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
473
|
+
replacements = retainCompaction(replacements, {
|
|
474
|
+
payload,
|
|
475
|
+
sequence
|
|
476
|
+
});
|
|
477
|
+
} else clearings = retainCompaction(clearings, {
|
|
478
|
+
payload,
|
|
479
|
+
sequence
|
|
480
|
+
});
|
|
461
481
|
}
|
|
462
482
|
let summaryEmitted = false;
|
|
463
|
-
const retainedPrefix =
|
|
464
|
-
const replacementLength =
|
|
483
|
+
const retainedPrefix = replacements.some(({ payload }) => payload.kind === "rollover" && payload.runId === ownerRunId && ownerPrefixSequence <= payload.coversThrough) ? protectedContext?.content ?? [] : [];
|
|
484
|
+
const replacementLength = retainedPrefix.length + replacements.length;
|
|
465
485
|
if (seed?.frontier !== void 0) onBoundary?.({
|
|
466
486
|
...seed.frontier,
|
|
467
487
|
promptLength: replacementLength
|
|
468
488
|
});
|
|
469
489
|
const emitSummary = () => {
|
|
470
|
-
if (summaryEmitted ||
|
|
490
|
+
if (summaryEmitted || replacements.length === 0) return;
|
|
471
491
|
summaryEmitted = true;
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
492
|
+
state.all.push(...retainedPrefix);
|
|
493
|
+
for (const { payload: replacement } of replacements) {
|
|
494
|
+
const message = replacement.kind === "rollover" ? contextWindowMessage(contextWindowId(replacement.runId, replacement.turn), replacement.handoff) : Prompt.makeMessage("user", { content: [Prompt.makePart("text", { text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}` })] });
|
|
495
|
+
state.all.push(message);
|
|
496
|
+
if (replacement.kind !== "rollover" || replacement.runId !== ownerRunId) state.before.push(message);
|
|
497
|
+
}
|
|
475
498
|
};
|
|
476
499
|
const modelUsage = [];
|
|
477
500
|
let unobservedModelCalls = seed?.unobservedModelCalls ?? 0;
|
|
@@ -558,7 +581,7 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
558
581
|
pendingToolsForRun: false
|
|
559
582
|
};
|
|
560
583
|
});
|
|
561
|
-
yield* Stream.runForEach(
|
|
584
|
+
yield* Stream.runForEach(recordsForRun, (envelope) => Effect.gen(function* () {
|
|
562
585
|
const payload = envelope.record.payload;
|
|
563
586
|
if ((payload._tag === "RunCompleted" || payload._tag === "RunFailed") && payload.runId === ownerRunId || payload._tag === "SubmissionSettled" && runIdForSubmission(payload.submissionId) === ownerRunId) ownerTerminated = true;
|
|
564
587
|
if (payload._tag === "RunPolicyUsageReserved" && payload.runId === ownerRunId) {
|
|
@@ -570,7 +593,7 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
570
593
|
if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return;
|
|
571
594
|
if (payload._tag === "CompactionCreated") return;
|
|
572
595
|
if (seed !== void 0 && envelope.sequence <= seed.throughSequence && (payload._tag === "ModelResponseRecorded" || payload._tag === "ToolCallSettled")) return;
|
|
573
|
-
if (
|
|
596
|
+
if (replacements.some(({ payload }) => isCovered(envelope, payload))) {
|
|
574
597
|
if (payload._tag === "ModelResponseRecorded" && payload.runId === ownerRunId) {
|
|
575
598
|
const messages = yield* decodePromptMessages(payload.messages);
|
|
576
599
|
yield* accountResponse(envelope, payload, messages);
|
|
@@ -582,7 +605,7 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
582
605
|
if (payload._tag === "ModelResponseRecorded" || payload._tag === "ToolCallSettled") onBoundary?.({
|
|
583
606
|
sequence: envelope.sequence,
|
|
584
607
|
tag: payload._tag,
|
|
585
|
-
promptLength: replacementLength,
|
|
608
|
+
promptLength: Math.max(replacementLength, state.all.length),
|
|
586
609
|
...isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY) ? { terminalPriorRun: true } : {},
|
|
587
610
|
...incompleteToolTurns.has(envelope.record.recordId) || incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}
|
|
588
611
|
});
|
|
@@ -598,7 +621,7 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
598
621
|
slot.parts[slot.partIndex] = Prompt.makePart("tool-result", {
|
|
599
622
|
id: payload.toolCallId,
|
|
600
623
|
name: payload.toolName,
|
|
601
|
-
result:
|
|
624
|
+
result: clearings.some(({ payload }) => isCovered(envelope, payload)) ? CLEARED_TOOL_RESULT : payload.result,
|
|
602
625
|
isFailure: payload.isFailure,
|
|
603
626
|
providerExecuted: false
|
|
604
627
|
});
|
|
@@ -618,7 +641,7 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
|
|
|
618
641
|
if (state.pendingTools.length > 0 && state.pendingToolsForRun !== (payload.runId === ownerRunId)) state = yield* flushTools(state);
|
|
619
642
|
state.pendingTools.push({
|
|
620
643
|
record: payload,
|
|
621
|
-
cleared:
|
|
644
|
+
cleared: clearings.some(({ payload }) => isCovered(envelope, payload))
|
|
622
645
|
});
|
|
623
646
|
state = {
|
|
624
647
|
...state,
|
|
@@ -928,4 +951,4 @@ const turnResultsBatch = Effect.fn("RunJournal.turnResultsBatch")(function* (inp
|
|
|
928
951
|
//#endregion
|
|
929
952
|
export { workerOriginRecordId as $, subagentRequestedRecordId as A, toolCallUnknownRecordId as B, runStartedBatchId as C, subagentLineageBatchId as D, subagentJoinedRecordId as E, toolCallPreparedRecordId as F, turnCanonicalBatch as G, toolStepSettledRecordId as H, toolCallResolutionBatchId as I, turnResponseBatch as J, turnIdForRun as K, toolCallResolvedRecordId as L, subagentStartedRecordId as M, toolApprovalDecisionRecordId as N, subagentLineageRecordId as O, toolApprovalRequestRecordId as P, workerInputRecordId as Q, toolCallResultBatchId as R, runIdForSubmission as S, subagentJoinBatchId as T, turnApprovalsBatchId as U, toolStepSettledBatchId as V, turnBatchId as W, turnResultsBatch as X, turnResponseBatchId as Y, turnResultsBatchId as Z, promptFromCanonicalRecords as _, childIdempotencyKeyFor as a, runDurationBatchId as b, compactionRecordId as c, modelResponseInterruptedBatchId as d, workerReportRecordId as et, modelResponseInterruptedRecordId as f, projectRunJournalStream as g, projectRunJournal as h, approvalDecisionBatchId as i, subagentStartedBatchId as j, subagentRequestedBatchId as k, firstWorkerInputRecordId as l, peerMessageRecordId as m, RunJournal_exports as n, childThreadIdFor as o, modelResponseRecordId as p, turnPreparedBatchId as q, agentUpdateRecordId as r, compactionBatchId as s, RunJournalError as t, makeJournalMetadata as tt, markUnknownBatchId as u, runCompletedRecordId as v, runStartedRecordId as w, runDurationRecordId as x, runCompletionDigest as y, toolCallSettledRecordId as z };
|
|
930
953
|
|
|
931
|
-
//# sourceMappingURL=RunJournal-
|
|
954
|
+
//# sourceMappingURL=RunJournal-Gd83HYqG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RunJournal-Gd83HYqG.mjs","names":[],"sources":["../src/durable/internal/journal-metadata.ts","../src/durable/RunJournal.ts"],"sourcesContent":["import { type RunId } from \"../../core/Identifiers.ts\";\nimport {\n type CanonicalRecordEnvelope,\n type CompactionCreated,\n type ToolCallPrepared,\n type ToolCallSettled,\n} from \"../Records.ts\";\nimport { type JournalCheckpointSeed } from \"./journal-checkpoint.ts\";\n\n/** Metadata for one exact canonical prefix, including the same optional checkpoint seed. */\nexport interface JournalMetadata {\n readonly ownerRunId: RunId | undefined;\n readonly seed: JournalCheckpointSeed | undefined;\n readonly firstSequenceByRun: ReadonlyMap<string, number>;\n readonly lastResponseSequenceByRun: ReadonlyMap<string, number>;\n readonly terminalSequenceByRun: ReadonlyMap<string, number>;\n readonly settledSpans: ReadonlyArray<{\n readonly from: number;\n readonly to: number;\n readonly runId: RunId;\n }>;\n readonly toolExecutionEvidence: ReadonlySet<string>;\n readonly settledToolCallRecordIds: ReadonlySet<string>;\n readonly settledById: ReadonlyMap<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >;\n readonly compactions: ReadonlyArray<{\n readonly payload: CompactionCreated;\n readonly sequence: number;\n }>;\n}\n\nexport const toolExecutionKey = (\n call: Pick<ToolCallPrepared, \"runId\" | \"turn\" | \"toolCallId\">,\n): string => JSON.stringify([call.runId, call.turn, call.toolCallId]);\n\n/**\n * Attempt-local metadata collector. Feed every validated record exactly once, in canonical order,\n * including records omitted from the control view. A snapshot is independent of later suffix\n * additions and may only accompany a replay stream bounded at that same captured tail.\n */\nexport const makeJournalMetadata = (\n ownerRunId: RunId | undefined,\n seed?: JournalCheckpointSeed,\n) => {\n const firstSequenceByRun = new Map<string, number>();\n\n if (seed?.firstSequence !== undefined) firstSequenceByRun.set(seed.runId, seed.firstSequence);\n const lastResponseSequenceByRun = new Map<string, number>();\n const terminalSequenceByRun = new Map<string, number>();\n\n const settledSpans: Array<{ readonly from: number; readonly to: number; readonly runId: RunId }> =\n [];\n\n const toolExecutionEvidence = new Set<string>();\n const settledToolCallRecordIds = new Set<string>();\n\n const settledById = new Map<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >();\n\n const compactions: Array<{ readonly payload: CompactionCreated; readonly sequence: number }> = [];\n\n return {\n add: (envelope: CanonicalRecordEnvelope): void => {\n const payload = envelope.record.payload;\n\n if (\n (payload._tag === \"RunCompleted\" ||\n payload._tag === \"RunFailed\" ||\n payload._tag === \"SubmissionSettled\") &&\n payload.runId !== undefined &&\n !terminalSequenceByRun.has(payload.runId)\n )\n terminalSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"CompactionCreated\") {\n compactions.push({ payload, sequence: envelope.sequence });\n\n return;\n }\n if (\n \"runId\" in payload &&\n typeof payload.runId === \"string\" &&\n !firstSequenceByRun.has(payload.runId)\n )\n firstSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"ModelResponseRecorded\") {\n lastResponseSequenceByRun.set(payload.runId, envelope.sequence);\n } else if (payload._tag === \"ToolCallPrepared\" || payload._tag === \"ToolCallUnknown\") {\n toolExecutionEvidence.add(toolExecutionKey(payload));\n } else if (payload._tag === \"ToolCallSettled\") {\n settledToolCallRecordIds.add(envelope.record.recordId);\n if (payload.runId === ownerRunId)\n settledById.set(envelope.record.recordId, {\n isFailure: payload.isFailure,\n ...(payload.toolSelection === undefined\n ? {}\n : { toolSelection: payload.toolSelection }),\n ...(payload.budgetRejected === undefined\n ? {}\n : { budgetRejected: payload.budgetRejected }),\n });\n const from = lastResponseSequenceByRun.get(payload.runId);\n\n if (from !== undefined && from < envelope.sequence)\n settledSpans.push({ from, to: envelope.sequence, runId: payload.runId });\n }\n },\n snapshot: (): JournalMetadata => ({\n ownerRunId,\n seed,\n firstSequenceByRun: new Map(firstSequenceByRun),\n lastResponseSequenceByRun: new Map(lastResponseSequenceByRun),\n terminalSequenceByRun: new Map(terminalSequenceByRun),\n settledSpans: [...settledSpans],\n toolExecutionEvidence: new Set(toolExecutionEvidence),\n settledToolCallRecordIds: new Set(settledToolCallRecordIds),\n settledById: new Map(settledById),\n compactions: [...compactions],\n }),\n };\n};\n","import { type Crypto, Effect, Schema, Stream, type DateTime } from \"effect\";\nimport { Prompt } from \"effect/unstable/ai\";\n\nimport { ThreadId, RunId, ToolCallId, TurnId, type SubmissionId } from \"../core/Identifiers.ts\";\nimport { type ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport { type Selection, type Snapshot } from \"../core/ToolExposure.ts\";\nimport type { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, summarizeModelUsage, type RunUsageSummary } from \"../core/Usage.ts\";\nimport type { WorkerRef } from \"../core/Worker.ts\";\nimport {\n CLEARED_TOOL_RESULT,\n COMPACTION_SUMMARY_PREFIX,\n contextWindowId,\n contextWindowMessage,\n} from \"../engine/Compaction.ts\";\nimport { digestJson, type DigestError } from \"./Digest.ts\";\nimport { type JournalCheckpointSeed } from \"./internal/journal-checkpoint.ts\";\nimport {\n makeJournalMetadata,\n toolExecutionKey,\n type JournalMetadata,\n} from \"./internal/journal-metadata.ts\";\nimport {\n BatchId,\n CanonicalBatch,\n CompactionCreated,\n ModelResponseRecorded,\n PersistedJson,\n RecordEnvelope,\n RecordId,\n RunCompleted,\n ToolCallSettled,\n type CanonicalRecordEnvelope,\n type CanonicalSequence,\n type DeploymentId,\n type ProducerId,\n} from \"./Records.ts\";\nimport { IdempotencyKey } from \"./SubmissionLedger.ts\";\n\n/** A canonical record could not be projected into Run/Prompt state. */\nexport class RunJournalError extends Schema.TaggedError<RunJournalError>()(\"RunJournalError\", {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n}) {}\n\nconst journalError = (message: string, cause?: unknown): RunJournalError =>\n cause === undefined\n ? RunJournalError.make({ message })\n : RunJournalError.make({ message, cause });\n\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\nconst decodeBatchId = Schema.decodeSync(BatchId);\nconst decodeRecordId = Schema.decodeSync(RecordId);\n\n/**\n * Deterministic Run identity pinned per Submission (plan §Coordinator flow). Every Attempt of one\n * Submission shares this Run identity, so canonical per-Turn records from different Attempts\n * belong to one logical Run.\n */\nexport const runIdForSubmission = (submissionId: SubmissionId): RunId =>\n decodeRunId(`run:${submissionId}`);\n\n/** Stable canonical clock identity shared by every Attempt of one Run. */\nexport const runStartedRecordId = (runId: RunId): RecordId => decodeRecordId(`run-start:${runId}`);\n\nexport const runStartedBatchId = (runId: RunId): BatchId => decodeBatchId(`run-start:${runId}`);\n\nexport const runDurationRecordId = (runId: RunId): RecordId =>\n decodeRecordId(`run-duration:${runId}`);\n\nexport const runDurationBatchId = (runId: RunId): BatchId => decodeBatchId(`run-duration:${runId}`);\n\n/** Deterministic Turn identity: Attempt-independent for one (Run, canonical turn) pair. */\nexport const turnIdForRun = (runId: RunId, turn: number): TurnId =>\n decodeTurnId(`turn:${runId}:${turn}`);\n\n/** Deterministic batch identity of one committed canonical no-tool Turn (P4 single-batch shape). */\nexport const turnBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESPONSE commit (plan §2.1 commit 1):\n * the assistant response plus pending steering becomes canonical BEFORE approval preflight and\n * tool preparation, creating the durability §15 \"resume tool scheduling\" window.\n */\nexport const turnResponseBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-response:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESULTS commit (plan §2.1 commit 5):\n * every `ToolCallSettled` record of the Turn, in declaration order, model-visible atomically.\n */\nexport const turnResultsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-results:${runId}:${turn}`);\n\n/**\n * Deterministic per-call late-settle batch identity used by the resolution path when one\n * recovered/resolved call settles outside its Turn's results batch. Record identity\n * (`tool-settled:{runId}:{turn}:{toolCallId}`) dedupes double-settles across both paths.\n */\nexport const toolCallResultBatchId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`turn-results:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallPrepared` commit (plan §2.1 commit 3). */\nexport const turnPreparedBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-prepared:${runId}:${turn}`);\n\n/**\n * Deterministic identity of one pre-Turn compaction record (RUN-026,\n * RUN-026). Keyed by Run, Turn, and kind — the engine performs at most one\n * threshold compaction per Turn plus at most one overflow-forced summarize,\n * so a superseding Attempt that re-decides the same compaction replays the\n * batch identity instead of duplicating the record.\n */\nexport const compactionRecordId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): RecordId => decodeRecordId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic batch identity of one compaction append (same string as its record id). */\nexport const compactionBatchId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): BatchId => decodeBatchId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic canonical record identity of one Turn's `ModelResponseRecorded` record. */\nexport const modelResponseRecordId = (runId: RunId, turn: number): RecordId =>\n decodeRecordId(`model-response:${runId}:${turn}`);\n\n/** Terminal Tool completion marker committed atomically with its settled Tool result. */\nexport const runCompletedRecordId = (runId: RunId): RecordId =>\n decodeRecordId(`run-completed:${runId}`);\n\n/** Native source reservation locator, including the first admission of a continuing worker. */\nexport const workerInputRecordId = (messageId: IdempotencyKey): RecordId =>\n decodeRecordId(`worker-input:${messageId}`);\n\n/** Source-owned first reservation; native worker identity is minted from its first message. */\nexport const firstWorkerInputRecordId = (worker: WorkerRef): RecordId =>\n decodeRecordId(`worker-input:${worker.threadId}`);\n\nexport const workerOriginRecordId = (threadId: ThreadId): RecordId =>\n decodeRecordId(`worker-origin:${threadId}`);\n\nexport const workerReportRecordId = (messageId: IdempotencyKey): RecordId =>\n decodeRecordId(`worker-report:${messageId}`);\n\nexport const peerMessageRecordId = (messageId: IdempotencyKey): RecordId =>\n decodeRecordId(messageId);\n\n/** Same immutable tuple used by native update admission; callers never parse its hash. */\nexport const agentUpdateRecordId = Effect.fn(\"RunJournal.agentUpdateRecordId\")(function* (\n threadId: ThreadId,\n runId: RunId,\n updateId: IdempotencyKey,\n) {\n return decodeRecordId(`agent-update:${yield* digestJson([threadId, runId, updateId])}`);\n});\n\n/** Deterministic canonical record identity of one Turn's `ToolCallSettled` record. */\nexport const toolCallSettledRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-settled:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallPrepared` record. */\nexport const toolCallPreparedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-prepared:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallUnknown` marking append. */\nexport const markUnknownBatchId = (submissionId: SubmissionId, turn: number): BatchId =>\n decodeBatchId(`mark-unknown:${submissionId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallUnknown` record. */\nexport const toolCallUnknownRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-unknown:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's resolution append (DUR-017). */\nexport const toolCallResolutionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`resolve:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallResolved` record. */\nexport const toolCallResolvedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-resolved:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one accepted Durable Step result. The one-record batch reuses the\n * SAME string, so batch idempotency plus the epoch fence realize the durability §11\n * racing-writers rule: only the fenced winner's record commits; the loser replays it.\n * A versioned JSON tuple keeps separator characters in each identity component distinct.\n * Replay derives this key from the structured payload, including records with legacy IDs.\n */\nexport const toolStepSettledRecordId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): RecordId => decodeRecordId(JSON.stringify([\"step@2\", runId, toolCallId, stepName]));\n\n/** Deterministic batch identity of one Durable Step commit (same string as its record id). */\nexport const toolStepSettledBatchId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): BatchId => decodeBatchId(toolStepSettledRecordId(runId, toolCallId, stepName));\n\n/** Deterministic batch identity of one Turn's canonical approval-request append (plan §2.6). */\nexport const turnApprovalsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-approvals:${runId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalRequested` record. */\nexport const toolApprovalRequestRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-request:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's canonical approval-decision append. */\nexport const approvalDecisionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`approval-decision:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalDecided` record. */\nexport const toolApprovalDecisionRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-decision:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one superseded Attempt's `ModelResponseInterrupted` audit record\n * (durability §9). Keyed by the superseded epoch, so each interrupted ownership period is\n * recorded at most once; the one-record batch reuses the same string.\n */\nexport const modelResponseInterruptedRecordId = (runId: RunId, supersededEpoch: number): RecordId =>\n decodeRecordId(`interrupted:${runId}:${supersededEpoch}`);\n\n/** Deterministic batch identity of one `ModelResponseInterrupted` append (same string). */\nexport const modelResponseInterruptedBatchId = (runId: RunId, supersededEpoch: number): BatchId =>\n decodeBatchId(`interrupted:${runId}:${supersededEpoch}`);\n\nconst decodeThreadId = Schema.decodeSync(ThreadId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentRequested` record.\n * The one-record batch reuses the same string, so batch\n * idempotency plus the parent epoch fence make the request append exactly-once-canonical.\n */\nexport const subagentRequestedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-requested:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentRequested` append (same string). */\nexport const subagentRequestedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-requested:${runId}:${toolCallId}`);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentStarted` record.\n * Recovery's start-link repair appends the EXACT same record\n * under this identity, so a raced repair replays instead of duplicating (SUB-016/SUB-017).\n */\nexport const subagentStartedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-started:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentStarted` append (same string). */\nexport const subagentStartedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-started:${runId}:${toolCallId}`);\n\n/**\n * Deterministic batch identity of one parent Tool Call's atomic settlement join: the\n * `SubagentJoined` record plus the parent's `ToolCallSettled` record (its existing\n * `tool-settled:{runId}:{turn}:{toolCallId}` identity) commit as ONE canonical batch (SUB-019).\n */\nexport const subagentJoinBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-join:${runId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one parent Tool Call's `SubagentJoined` record. */\nexport const subagentJoinedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-joined:${runId}:${toolCallId}`);\n\n/**\n * Deterministic identity of one child Thread's `SubagentLineageRecorded` record.\n * Its own single-record batch reuses the same string so the generic\n * `thread-created:{cid}` batch identity is never contradicted.\n */\nexport const subagentLineageRecordId = (threadId: ThreadId): RecordId =>\n decodeRecordId(`subagent-lineage:${threadId}`);\n\n/** Deterministic batch identity of one `SubagentLineageRecorded` append (same string). */\nexport const subagentLineageBatchId = (threadId: ThreadId): BatchId =>\n decodeBatchId(`subagent-lineage:${threadId}`);\n\n/**\n * Deterministic intended child Thread identity: the\n * parent Submission and Tool Call pair addresses exactly one child Thread, so a replayed\n * establishment converges on the one existing child (SUB-016).\n */\nexport const childThreadIdFor = (\n parentSubmissionId: SubmissionId,\n toolCallId: ToolCallId,\n): ThreadId => decodeThreadId(`subagent:${parentSubmissionId}:${toolCallId}`);\n\n/**\n * Deterministic child admission idempotency key: scoped to\n * the parent Run and Tool Call identity, so duplicate admission attempts resolve through the\n * ledger's idempotency contract to one child Receipt (SUB-016, SUB-031). The ledger key is\n * bounded (256); coordinator-minted Run and Tool Call identities stay far below that bound.\n */\nexport const childIdempotencyKeyFor = (\n parentRunId: RunId,\n toolCallId: ToolCallId,\n): IdempotencyKey => decodeIdempotencyKey(`subagent:${parentRunId}:${toolCallId}`);\n\nconst decodePromptMessages = Effect.fn(\"RunJournal.decodePromptMessages\")(\n (messages: PersistedJson): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n Schema.decodeUnknownEffect(Prompt.Prompt)(messages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical messages are not Schema-encoded Prompt messages\", cause),\n ),\n ),\n);\n\ninterface PendingSettledTool {\n readonly record: ToolCallSettled;\n /** RUN-026: a `clear-tool-results` compaction covers this record's sequence. */\n readonly cleared: boolean;\n}\n\nconst toolMessageFromSettled = Effect.fn(\"RunJournal.toolMessageFromSettled\")(\n (settled: ReadonlyArray<PendingSettledTool>): Effect.Effect<Prompt.Message, RunJournalError> =>\n Effect.try({\n try: () =>\n Prompt.makeMessage(\"tool\", {\n content: settled.map(({ record, cleared }) =>\n Prompt.makePart(\"tool-result\", {\n id: record.toolCallId,\n name: record.toolName,\n result: cleared ? CLEARED_TOOL_RESULT : record.result,\n isFailure: record.isFailure,\n providerExecuted: false,\n }),\n ),\n }),\n catch: (cause) => journalError(\"Unable to rebuild Tool message from ToolCallSettled\", cause),\n }),\n);\n\n/**\n * Pure canonical projection of one Run's durable execution state.\n *\n * Prompt reconstruction contract (D8):\n *\n * - `ModelResponseRecorded.messages` carries the Schema-encoded Prompt messages the Turn appended\n * to the model-visible prompt — for the Run's FIRST committed Turn that includes the evaluated\n * instruction and user-input messages, for later Turns only the assistant response messages.\n * Tool messages are excluded from `messages`.\n * - `ToolCallSettled` records (committed in the same per-Turn batch, in declaration order)\n * deterministically rebuild the Turn's single Tool message.\n * - `UserInputRecorded` records input, with a Submission identity only for durable admission. Its\n * Prompt-visible form (instructions + user message) becomes canonical inside the owning Run's\n * first `ModelResponseRecorded`. The projection consumes it only for Run correlation.\n * - Immediate retained history uses `ModelCompleted.messages` for the successful Run's exact\n * native Prompt suffix, including any input examples. It has no resumable Turn state.\n */\n/** Cumulative committed usage of the projected Run (RUN-023 resume re-seed). */\nexport interface RunJournalUsage {\n readonly modelCalls: number;\n /** Known accounting gaps retained across Attempts without changing numeric usage totals. */\n readonly unobservedModelCalls?: number | undefined;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly lastInputTokens: number;\n readonly lastOutputTokens: number;\n /** Cumulative persisted spend of the projected Run's committed calls (RUN-023). */\n readonly costMicrousd: number;\n /** Canonical per-call detail used for settlement aggregation and recovery. */\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n /** Detailed usage of retired records, grouped without retaining per-call payloads. */\n readonly summarizedModelUsage?: RunUsageSummary | undefined;\n}\n\nexport interface RunJournalProjection {\n readonly toolSelection?: Selection | undefined;\n readonly policyUsage: RunPolicyUsage;\n /** Canonical projection for the requested Run; may end at its resumable Tool declaration. */\n readonly prompt: Prompt.Prompt;\n /** Prior-Run history with model-only unknown results closing incomplete application calls. */\n readonly historyBefore: Prompt.Prompt;\n /** Number of canonical Turns already committed for the projected Run. */\n readonly committedTurns: number;\n /** Summed per-call usage of the projected Run's committed responses; zeros for records predating usage capture. */\n readonly usage: RunJournalUsage;\n /** Latest committed context window identity, retained across ownership changes. */\n readonly contextWindowId?: string | undefined;\n /** Canonical evaluated instructions and initial input for this Run, independent of the view. */\n readonly protectedContext?: Prompt.Prompt | undefined;\n /** Last successful singleton Tool awaiting possible context-control interpretation by the engine. */\n readonly pendingContextToolCallId?: string | undefined;\n}\n\ninterface ProjectedResponseUsage {\n readonly modelCalls: number;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd: number;\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n}\n\nconst projectedResponseUsage = (\n response: ModelResponseRecorded,\n): Effect.Effect<ProjectedResponseUsage, RunJournalError> =>\n Effect.gen(function* () {\n const calls = response.modelUsage;\n\n if (calls === undefined) {\n return {\n modelCalls: 1,\n inputTokens: response.inputTokens ?? 0,\n outputTokens: response.outputTokens ?? 0,\n costMicrousd: response.costMicrousd ?? 0,\n modelUsage: [],\n };\n }\n if (calls.length === 0) {\n return yield* journalError(\"A canonical modelUsage list must not be empty\");\n }\n\n const summary = yield* summarizeModelUsage(calls).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical model usage exceeds accounting bounds\", cause),\n ),\n );\n\n if (\n (response.inputTokens !== undefined && response.inputTokens !== summary.inputTokens.total) ||\n (response.outputTokens !== undefined &&\n response.outputTokens !== summary.outputTokens.total) ||\n (response.costMicrousd !== undefined && response.costMicrousd !== summary.costMicrousd)\n ) {\n return yield* journalError(\"Canonical detailed and aggregate model usage disagree\");\n }\n\n return {\n modelCalls: summary.modelCalls,\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n modelUsage: calls,\n };\n });\n\nconst addProjectedUsage = (\n field: string,\n left: number,\n right: number,\n): Effect.Effect<number, RunJournalError> =>\n Schema.decodeEffect(Schema.Natural)(left + right).pipe(\n Effect.mapError((cause) =>\n journalError(`Canonical projected usage exceeds safe-integer bounds at ${field}`, cause),\n ),\n );\n\ninterface FoldState {\n readonly all: Array<Prompt.Message>;\n readonly before: Array<Prompt.Message>;\n readonly pendingTools: Array<PendingSettledTool>;\n readonly pendingToolsForRun: boolean;\n readonly committedTurns: number;\n}\n\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\n\nconst declaredApplicationToolCallIds = (prompt: Prompt.Prompt): ReadonlyArray<string> => {\n const ids: Array<string> = [];\n\n for (const message of prompt.content) {\n if (message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !part.providerExecuted) ids.push(part.id);\n }\n }\n\n return ids;\n};\n\n/**\n * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (preparation,\n * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to\n * the model-visible Prompt, and — unlike the P4 tags — they do NOT split a contiguous\n * `ToolCallSettled` group into separate Tool messages, so a late-settled call's audit records\n * cannot change the replayed prompt shape.\n *\n * The four S2 Subagent lifecycle tags are prompt-transparent for the same reason (spec §5/§11):\n * the parent prompt never carries child transcript or establishment evidence — the joined child\n * result reaches the model exclusively through the paired `ToolCallSettled` record, and the\n * child-log lineage record is not model input.\n */\nconst PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([\n \"RunPolicyUsageReserved\",\n \"RunStarted\",\n \"RunDurationExhausted\",\n \"ToolCallPrepared\",\n \"ToolCallUnknown\",\n \"ToolCallResolved\",\n \"ToolStepSettled\",\n \"ToolApprovalRequested\",\n \"ToolApprovalDecided\",\n \"ModelResponseInterrupted\",\n \"SubagentRequested\",\n \"SubagentStarted\",\n \"SubagentJoined\",\n \"SubagentLineageRecorded\",\n \"WorkerInputRequested\",\n \"WorkerOriginRecorded\",\n \"WorkerInputCompleted\",\n \"WorkerReportPrepared\",\n \"AgentUpdateEmitted\",\n \"WorkerReportRefused\",\n \"PeerMessagePrepared\",\n \"SubtreeBudgetReserved\",\n]);\n\n/**\n * Pure projection: rebuild one Run's resume state from canonical records (DUR-015). Canonical\n * order is authoritative; the fold projects each `ModelResponseRecorded` Turn and the\n * owning Run's resumable incomplete Tool Turn. It flushes each contiguous group of valid `ToolCallSettled` records into one Tool message,\n * exactly mirroring the per-Turn commit shape produced by `turnCanonicalBatch` (no-tool Turns) and\n * by the\n * `turnResponseBatch`/`turnResultsBatch` split (tool-declaring Turns). The Phase 5 audit tags\n * are skipped transparently, so split-batch commits replay to the same prompt as P4 single-batch\n * commits.\n *\n * An incomplete application Tool turn remains visible while projecting its owning Run so active\n * recovery can resume the declared batch. It is not a valid model-visible Turn boundary for a\n * later Run until model-only unknown results close its missing calls. Those explanatory results\n * are never canonical settlements or evidence for compaction, recovery or accounting. Real\n * results replace them at the original declaration, including results appended after another Run.\n * Prior user intent and assistant text remain visible; prior system instructions do not.\n * Each Run retains the history preceding its start and its own continuation. Other Runs'\n * subsequent Turns cannot replace its input. Compaction covers only its creator's Run view;\n * a projection without an owner retains interleaved exchanges from the complete Thread history.\n */\n/** @internal Lightweight canonical boundaries collected without retaining record payloads. */\nexport interface JournalBoundary {\n readonly sequence: CanonicalSequence;\n readonly tag: \"ModelResponseRecorded\" | \"ToolCallSettled\";\n readonly promptLength: number;\n /** A declaration without all settled results requires terminal-prior-Run proof for coverage. */\n readonly incomplete?: true | undefined;\n /** The Run terminated after its last response and differs from the projection's owner. */\n readonly terminalPriorRun?: true | undefined;\n}\n\n/**\n * Reconstruct a fixed canonical prefix from a re-readable stream. The caller must keep the same\n * records visible on every traversal. The first collects compaction and settlement metadata;\n * rollovers additionally validate covered Tool batches before rebuilding Prompt and usage. Metadata and the\n * live Prompt remain resident; covered historical message/tool payloads do not. An uncompacted Prompt still grows\n * with its conversation, so hosts must configure an appropriate context compaction policy.\n * Prepared metadata must describe exactly this stream and seed through the same fixed tail;\n * it skips only the metadata scan, never covered-Tool validation or the canonical fold.\n * @internal\n */\nexport const projectRunJournalStream = Effect.fn(\"RunJournal.projectRunJournalStream\")(function* <\n E,\n R,\n>(\n records: Stream.Stream<CanonicalRecordEnvelope, E, R>,\n ownerRunId: RunId | undefined,\n onBoundary?: (boundary: JournalBoundary) => void,\n seed?: JournalCheckpointSeed,\n preparedMetadata?: JournalMetadata,\n): Effect.fn.Return<RunJournalProjection, RunJournalError | E, R> {\n if (seed !== undefined && seed.runId !== ownerRunId)\n return yield* journalError(\"Recovery checkpoint belongs to another Run\");\n\n let state: FoldState = {\n all: [],\n before: [],\n pendingTools: [],\n pendingToolsForRun: false,\n committedTurns: seed?.committedTurns ?? 0,\n };\n\n // RUN-026 pre-scan: valid compactions retire only their creator's Run view. A bound\n // stays below its own sequence and cannot split a visible response from its settled results.\n // Pruning and rollovers may cover complete owner-Run batches; a summarize record carries\n // its summary. Invalid records leave full history authoritative. A wider containing view\n // replaces earlier coverage, with equal bounds preferring the later record.\n // One span per settled record, paired with its declaring response the same\n // way the fold pairs them: a settled belongs to the most recent\n // ModelResponseRecorded of its Run. A bound inside (response, settled)\n // would orphan the tool message from its declaring response. Orphaned\n // settleds (filtered later by the fold) still contribute spans —\n // over-invalidating is the fail-safe direction.\n if (\n preparedMetadata !== undefined &&\n (preparedMetadata.ownerRunId !== ownerRunId || preparedMetadata.seed !== seed)\n )\n return yield* journalError(\"Prepared journal metadata belongs to another replay\");\n\n let metadata = preparedMetadata;\n\n if (metadata === undefined) {\n const collected = makeJournalMetadata(ownerRunId, seed);\n\n yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)));\n metadata = collected.snapshot();\n }\n\n const {\n firstSequenceByRun,\n lastResponseSequenceByRun,\n terminalSequenceByRun,\n settledSpans,\n toolExecutionEvidence,\n settledToolCallRecordIds,\n settledById,\n } = metadata;\n\n const declarationByResultSequence = new Map(settledSpans.map(({ from, to }) => [to, from]));\n\n const isInRunView = (\n sequence: number,\n payload: { readonly _tag: string; readonly runId?: RunId | undefined },\n runId: RunId | undefined,\n ): boolean => {\n if (runId === undefined || payload.runId === undefined || payload.runId === runId) return true;\n const first = firstSequenceByRun.get(runId) ?? Number.POSITIVE_INFINITY;\n\n return (\n sequence < first ||\n (payload._tag === \"ToolCallSettled\" &&\n (declarationByResultSequence.get(sequence) ?? Number.POSITIVE_INFINITY) < first)\n );\n };\n\n const compactions = metadata.compactions.filter(({ sequence, payload }) =>\n isInRunView(sequence, payload, ownerRunId),\n );\n\n const recordsForRun = records.pipe(\n Stream.filter(({ sequence, record: { payload } }) =>\n isInRunView(sequence, payload, ownerRunId),\n ),\n );\n\n const isCovered = (envelope: CanonicalRecordEnvelope, compaction: CompactionCreated): boolean =>\n envelope.sequence <= compaction.coversThrough &&\n isInRunView(envelope.sequence, envelope.record.payload, compaction.runId);\n\n const settledCoverage = compactions.reduce(\n (through, { payload }) =>\n payload.kind !== \"summarize\" ? Math.max(through, payload.coversThrough) : through,\n 0,\n );\n\n // Terminality changes only prompt coverage; it never settles or resolves the Tool Call.\n // Compare against the compaction's Run and sequence, independent of the replay's owner.\n const isTerminalPriorRun = (\n candidateRunId: RunId,\n compactionRunId: RunId | undefined,\n beforeSequence: number,\n ): boolean => {\n const terminal = terminalSequenceByRun.get(candidateRunId);\n\n return (\n candidateRunId !== compactionRunId &&\n terminal !== undefined &&\n terminal < beforeSequence &&\n terminal > (lastResponseSequenceByRun.get(candidateRunId) ?? 0)\n );\n };\n\n const incompleteResponseSequences: Array<{ readonly sequence: number; readonly runId: RunId }> =\n [];\n\n let ownerPrefixSequence = seed?.firstSequence ?? Number.POSITIVE_INFINITY;\n\n let protectedContext: Prompt.Prompt | undefined =\n seed?.protectedContext === undefined\n ? undefined\n : yield* decodePromptMessages(seed.protectedContext);\n\n if (settledCoverage > 0) {\n yield* Stream.runForEach(recordsForRun, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (payload._tag !== \"ModelResponseRecorded\" || envelope.sequence > settledCoverage) return;\n const messages = yield* decodePromptMessages(payload.messages);\n const declared = declaredApplicationToolCallIds(messages);\n\n for (const id of declared) {\n const callId = yield* Schema.decodeEffect(ToolCallId)(id).pipe(\n Effect.mapError((cause) =>\n journalError(\"Failed to decode a declared Tool Call ID\", cause),\n ),\n );\n\n if (\n !settledToolCallRecordIds.has(\n toolCallSettledRecordId(payload.runId, payload.turn, callId),\n )\n ) {\n incompleteResponseSequences.push({ sequence: envelope.sequence, runId: payload.runId });\n break;\n }\n }\n if (\n payload.runId === ownerRunId &&\n payload.turn === 1 &&\n payload.runScopedPrefixLength !== undefined\n ) {\n ownerPrefixSequence = envelope.sequence;\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n }),\n );\n }\n\n const boundIsValid = (payload: CompactionCreated, ownSequence: number): boolean => {\n const { runId, coversThrough } = payload;\n\n if (coversThrough <= 0 || coversThrough >= ownSequence) return false;\n if (seed !== undefined && ownSequence === seed.compaction.sequence)\n return (\n seed.compaction.record.payload._tag === \"CompactionCreated\" &&\n Schema.toEquivalence(CompactionCreated)(payload, seed.compaction.record.payload)\n );\n const ownerFirst = firstSequenceByRun.get(runId);\n\n if (payload.kind === \"summarize\" && ownerFirst !== undefined && coversThrough >= ownerFirst)\n return false;\n if (\n payload.kind !== \"summarize\" &&\n incompleteResponseSequences.some(\n (response) =>\n response.sequence <= coversThrough &&\n isInRunView(\n response.sequence,\n { _tag: \"ModelResponseRecorded\", runId: response.runId },\n runId,\n ) &&\n !isTerminalPriorRun(response.runId, runId, ownSequence),\n )\n )\n return false;\n for (const span of settledSpans) {\n if (\n span.from <= coversThrough &&\n coversThrough < span.to &&\n isInRunView(span.from, { _tag: \"ModelResponseRecorded\", runId: span.runId }, runId)\n )\n return false;\n }\n\n return true;\n };\n\n type CompactionView = (typeof compactions)[number];\n\n let replacements: ReadonlyArray<CompactionView> = [];\n let clearings: ReadonlyArray<CompactionView> = [];\n\n const retainCompaction = (views: ReadonlyArray<CompactionView>, next: CompactionView) => {\n // Independent Run views overlap without containing one another. Retire an overlay only\n // when the replacement actually contains its view, not merely a larger sequence number.\n if (\n views.some(\n (prior) =>\n prior.payload.coversThrough > next.payload.coversThrough &&\n isInRunView(next.sequence, next.payload, prior.payload.runId),\n )\n )\n return views;\n\n return [\n ...views.filter(\n (prior) =>\n next.payload.coversThrough < prior.payload.coversThrough ||\n !isInRunView(prior.sequence, prior.payload, next.payload.runId),\n ),\n next,\n ];\n };\n\n let latestWindowId: string | undefined = seed?.contextWindowId;\n let latestWindowSequence = seed?.throughSequence ?? -1;\n let rolloverCoveredThrough = 0;\n\n for (const { payload, sequence } of compactions) {\n if (!boundIsValid(payload, sequence)) continue;\n if (payload.kind === \"rollover\" && sequence > latestWindowSequence) {\n latestWindowId = contextWindowId(payload.runId, payload.turn);\n latestWindowSequence = sequence;\n }\n if (payload.kind === \"rollover\")\n rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough);\n if (payload.kind === \"summarize\" || payload.kind === \"rollover\") {\n if (payload.kind === \"summarize\" && payload.summary === undefined) continue;\n replacements = retainCompaction(replacements, { payload, sequence });\n } else clearings = retainCompaction(clearings, { payload, sequence });\n }\n let summaryEmitted = false;\n\n const retainedPrefix = replacements.some(\n ({ payload }) =>\n payload.kind === \"rollover\" &&\n payload.runId === ownerRunId &&\n ownerPrefixSequence <= payload.coversThrough,\n )\n ? (protectedContext?.content ?? [])\n : [];\n\n const replacementLength = retainedPrefix.length + replacements.length;\n\n if (seed?.frontier !== undefined)\n onBoundary?.({ ...seed.frontier, promptLength: replacementLength });\n\n const emitSummary = () => {\n if (summaryEmitted || replacements.length === 0) return;\n summaryEmitted = true;\n state.all.push(...retainedPrefix);\n for (const { payload: replacement } of replacements) {\n const message =\n replacement.kind === \"rollover\"\n ? contextWindowMessage(\n contextWindowId(replacement.runId, replacement.turn),\n replacement.handoff,\n )\n : Prompt.makeMessage(\"user\", {\n content: [\n Prompt.makePart(\"text\", {\n text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}`,\n }),\n ],\n });\n\n state.all.push(message);\n if (replacement.kind !== \"rollover\" || replacement.runId !== ownerRunId)\n state.before.push(message);\n }\n };\n\n const modelUsage: Array<ModelCallUsage> = [];\n let unobservedModelCalls = seed?.unobservedModelCalls ?? 0;\n\n const usage = {\n modelCalls: seed?.modelCalls ?? 0,\n inputTokens: seed?.inputTokens ?? 0,\n outputTokens: seed?.outputTokens ?? 0,\n lastInputTokens: seed?.lastInputTokens ?? 0,\n lastOutputTokens: seed?.lastOutputTokens ?? 0,\n costMicrousd: seed?.costMicrousd ?? 0,\n modelUsage,\n ...(seed === undefined ? {} : { summarizedModelUsage: seed.summarizedModelUsage }),\n };\n\n let toolSelection = seed?.toolSelection;\n let usageTurn = seed?.committedTurns ?? 0;\n\n const incompleteToolTurns = new Set<string>();\n const incompleteToolCalls = new Set<string>();\n let pendingContextToolCallId: string | undefined;\n let ownerTerminated = false;\n\n const policyUsage = {\n committedTurns: seed?.policyUsage.committedTurns ?? 0,\n toolCalls: seed?.policyUsage.toolCalls ?? 0,\n programmaticToolCalls: seed?.policyUsage.programmaticToolCalls ?? 0,\n consecutiveToolFailures: seed?.policyUsage.consecutiveToolFailures ?? 0,\n finalizationUsed: seed?.policyUsage.finalizationUsed ?? false,\n };\n\n const accountResponse = Effect.fn(\"RunJournal.accountResponse\")(function* (\n envelope: CanonicalRecordEnvelope,\n payload: ModelResponseRecorded,\n messages: Prompt.Prompt,\n ) {\n const record = envelope.record;\n\n const declared = declaredApplicationToolCallIds(messages);\n const declaredRecordIds: Array<RecordId> = [];\n\n for (const id of declared) {\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(id),\n catch: (cause) => journalError(\"Failed to decode a declared Tool Call ID\", cause),\n });\n\n declaredRecordIds.push(toolCallSettledRecordId(payload.runId, payload.turn, toolCallId));\n }\n if (declaredRecordIds.some((recordId) => !settledToolCallRecordIds.has(recordId))) {\n incompleteToolTurns.add(envelope.record.recordId);\n for (const recordId of declaredRecordIds) incompleteToolCalls.add(recordId);\n }\n if (payload.runId !== ownerRunId) return;\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (payload.turn === 1 && payload.runScopedPrefixLength !== undefined) {\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n\n const responseUsage = yield* projectedResponseUsage(payload);\n\n unobservedModelCalls = yield* addProjectedUsage(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n payload.unobservedModelCalls ?? 0,\n );\n\n usage.modelCalls = yield* addProjectedUsage(\n \"modelCalls\",\n usage.modelCalls,\n responseUsage.modelCalls,\n );\n usage.inputTokens = yield* addProjectedUsage(\n \"inputTokens\",\n usage.inputTokens,\n responseUsage.inputTokens,\n );\n usage.outputTokens = yield* addProjectedUsage(\n \"outputTokens\",\n usage.outputTokens,\n responseUsage.outputTokens,\n );\n usage.costMicrousd = yield* addProjectedUsage(\n \"costMicrousd\",\n usage.costMicrousd,\n responseUsage.costMicrousd,\n );\n usage.modelUsage.push(...responseUsage.modelUsage);\n if (payload.turn > usageTurn) {\n usageTurn = payload.turn;\n usage.lastInputTokens = responseUsage.inputTokens;\n usage.lastOutputTokens = responseUsage.outputTokens;\n }\n\n policyUsage.committedTurns = Math.max(policyUsage.committedTurns, payload.turn);\n\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter((part) => part.type === \"tool-call\")\n : [],\n );\n\n const candidate = calls.length === 1 ? calls[0] : undefined;\n\n const candidateResult =\n candidate === undefined\n ? undefined\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${candidate.id}`);\n\n pendingContextToolCallId =\n candidate !== undefined &&\n !candidate.providerExecuted &&\n candidateResult?.isFailure === false &&\n candidateResult.budgetRejected !== true &&\n envelope.sequence > rolloverCoveredThrough\n ? candidate.id\n : undefined;\n\n policyUsage.toolCalls += calls.length;\n if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection;\n if (incompleteToolTurns.has(record.recordId)) return;\n for (const call of calls) {\n const result = call.providerExecuted\n ? messages.content\n .flatMap((message) => (message.role === \"assistant\" ? message.content : []))\n .find(\n (part) => part.type === \"tool-result\" && part.providerExecuted && part.id === call.id,\n )\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`);\n\n if (result === undefined || (\"budgetRejected\" in result && result.budgetRejected === true))\n continue;\n if (!(\"isFailure\" in result)) continue;\n if (!result.isFailure && \"toolSelection\" in result && result.toolSelection !== undefined)\n toolSelection = result.toolSelection;\n policyUsage.consecutiveToolFailures = result.isFailure\n ? policyUsage.consecutiveToolFailures + 1\n : 0;\n }\n });\n\n // Slots refer to the retained Prompt itself, not an additional history payload index.\n // Only still-unseen results retain a slot; late results fill the original declaration in place.\n const historicalResults = new Map<\n string,\n {\n readonly allIndex: number;\n readonly beforeIndex: number;\n readonly parts: Array<Prompt.ToolResultPart>;\n readonly partIndex: number;\n }\n >();\n\n let pendingToolOrder = new Map<string, number>();\n\n const flushTools = Effect.fn(\"RunJournal.flushTools\")(function* (\n current: FoldState,\n ): Effect.fn.Return<FoldState, RunJournalError> {\n if (current.pendingTools.length === 0) return current;\n\n // Suspension can persist an ordinary sibling before a delegated call joins. Model context\n // still uses declaration order, matching the live interpreter's completed results batch.\n const ordered = current.pendingTools.toSorted(\n (left, right) =>\n (pendingToolOrder.get(left.record.toolCallId) ?? Number.MAX_SAFE_INTEGER) -\n (pendingToolOrder.get(right.record.toolCallId) ?? Number.MAX_SAFE_INTEGER),\n );\n\n const toolMessage = yield* toolMessageFromSettled(ordered);\n\n current.all.push(toolMessage);\n if (!current.pendingToolsForRun) current.before.push(toolMessage);\n\n return {\n ...current,\n pendingTools: [],\n pendingToolsForRun: false,\n };\n });\n\n yield* Stream.runForEach(recordsForRun, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (\n ((payload._tag === \"RunCompleted\" || payload._tag === \"RunFailed\") &&\n payload.runId === ownerRunId) ||\n (payload._tag === \"SubmissionSettled\" &&\n runIdForSubmission(payload.submissionId) === ownerRunId)\n )\n ownerTerminated = true;\n\n if (payload._tag === \"RunPolicyUsageReserved\" && payload.runId === ownerRunId) {\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (\n payload.programmaticToolCalls < policyUsage.programmaticToolCalls ||\n (policyUsage.finalizationUsed && !payload.finalizationUsed)\n ) {\n return yield* journalError(\"Run policy reservations must be monotonic\");\n }\n policyUsage.programmaticToolCalls = payload.programmaticToolCalls;\n policyUsage.finalizationUsed = payload.finalizationUsed;\n }\n if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return;\n // The compaction record governs the fold (pre-scan) and contributes no\n // message of its own; records at or below the summarize bound render as\n // the one summary message emitted at the covered/kept transition.\n if (payload._tag === \"CompactionCreated\") return;\n if (\n seed !== undefined &&\n envelope.sequence <= seed.throughSequence &&\n (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\")\n )\n return;\n if (replacements.some(({ payload }) => isCovered(envelope, payload))) {\n // Retiring Prompt payloads does not retire the owning Run's policy or usage accounting.\n if (payload._tag === \"ModelResponseRecorded\" && payload.runId === ownerRunId) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n yield* accountResponse(envelope, payload, messages);\n state = { ...state, committedTurns: Math.max(state.committedTurns, payload.turn) };\n }\n if (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\") {\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: Math.max(replacementLength, state.all.length),\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ||\n incompleteToolCalls.has(envelope.record.recordId)\n ? { incomplete: true }\n : {}),\n });\n }\n\n return;\n }\n emitSummary();\n if (payload._tag === \"ToolCallSettled\") {\n if (payload.runId !== ownerRunId) {\n const slot = historicalResults.get(envelope.record.recordId);\n\n if (slot === undefined)\n return yield* journalError(\"Historical Tool result has no matching declaration\");\n const declared = slot.parts[slot.partIndex];\n\n if (declared?.id !== payload.toolCallId || declared.name !== payload.toolName)\n return yield* journalError(\"Historical Tool result differs from its declaration\");\n slot.parts[slot.partIndex] = Prompt.makePart(\"tool-result\", {\n id: payload.toolCallId,\n name: payload.toolName,\n result: clearings.some(({ payload }) => isCovered(envelope, payload))\n ? CLEARED_TOOL_RESULT\n : payload.result,\n isFailure: payload.isFailure,\n providerExecuted: false,\n });\n const message = Prompt.makeMessage(\"tool\", { content: [...slot.parts] });\n\n state.all[slot.allIndex] = message;\n state.before[slot.beforeIndex] = message;\n historicalResults.delete(envelope.record.recordId);\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n });\n\n return;\n }\n if (\n state.pendingTools.length > 0 &&\n state.pendingToolsForRun !== (payload.runId === ownerRunId)\n ) {\n state = yield* flushTools(state);\n }\n state.pendingTools.push({\n record: payload,\n cleared: clearings.some(({ payload }) => isCovered(envelope, payload)),\n });\n state = {\n ...state,\n pendingToolsForRun: payload.runId === ownerRunId,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + 1,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n\n return;\n }\n state = yield* flushTools(state);\n if (payload._tag === \"ModelCompleted\" && payload.messages !== undefined) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n for (const message of messages.content) {\n state.all.push(message);\n if (payload.runId !== ownerRunId) state.before.push(message);\n }\n\n return;\n }\n if (payload._tag !== \"ModelResponseRecorded\") return;\n const messages = yield* decodePromptMessages(payload.messages);\n const forRun = payload.runId === ownerRunId;\n\n pendingToolOrder = new Map(\n declaredApplicationToolCallIds(messages).map((id, index) => [id, index]),\n );\n\n yield* accountResponse(envelope, payload, messages);\n\n const visibleMessages = forRun\n ? messages.content\n : messages.content.filter((message) => message.role !== \"system\");\n\n for (const message of visibleMessages) {\n state.all.push(message);\n if (!forRun) state.before.push(message);\n }\n if (!forRun) {\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter(\n (part): part is Prompt.ToolCallPart =>\n part.type === \"tool-call\" && !part.providerExecuted,\n )\n : [],\n );\n\n if (calls.length > 0) {\n const parts = yield* Effect.forEach(calls, (call) =>\n Effect.gen(function* () {\n const callId = yield* Schema.decodeEffect(ToolCallId)(call.id).pipe(\n Effect.mapError((cause) => journalError(\"Invalid historical Tool Call ID\", cause)),\n );\n\n const operation = payload.toolOperations?.find(\n (operation) => operation.toolCallId === callId && operation.toolName === call.name,\n );\n\n // Only the recorded execution contract can prove that dispatch required a\n // preparation. Ordinary readonly calls may execute without one.\n const notExecuted =\n operation !== undefined &&\n (operation.executionClass !== \"readonly\" ||\n operation.executionKind !== \"ordinary\") &&\n !toolExecutionEvidence.has(\n toolExecutionKey({\n runId: payload.runId,\n turn: payload.turn,\n toolCallId: callId,\n }),\n );\n\n return Prompt.makePart(\"tool-result\", {\n id: call.id,\n name: call.name,\n result: notExecuted\n ? {\n _tag: \"ToolUnavailable\",\n toolName: call.name,\n execution: \"not-executed\",\n message:\n \"This earlier call never reached durable preparation and was not executed.\",\n }\n : {\n _tag: \"ToolOutcomeUnknown\",\n message:\n \"This earlier operation has no recorded outcome. It may have executed. Do not assume success or retry it; its original operation remains unresolved.\",\n },\n isFailure: true,\n providerExecuted: false,\n });\n }),\n );\n\n const allIndex = state.all.length;\n const beforeIndex = state.before.length;\n const message = Prompt.makeMessage(\"tool\", { content: parts });\n\n state.all.push(message);\n state.before.push(message);\n for (const [partIndex, call] of calls.entries()) {\n const callId = yield* Schema.decodeEffect(ToolCallId)(call.id).pipe(\n Effect.mapError((cause) => journalError(\"Invalid historical Tool Call ID\", cause)),\n );\n\n historicalResults.set(toolCallSettledRecordId(payload.runId, payload.turn, callId), {\n allIndex,\n beforeIndex,\n parts,\n partIndex,\n });\n }\n }\n }\n state = {\n ...state,\n committedTurns: forRun\n ? Math.max(state.committedTurns, payload.turn)\n : state.committedTurns,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n }),\n );\n emitSummary();\n state = yield* flushTools(state);\n\n const validatedPolicyUsage = yield* Schema.decodeEffect(RunPolicyUsage)(policyUsage).pipe(\n Effect.mapError((cause) =>\n journalError(\"Run policy accounting exceeds its Schema bounds\", cause),\n ),\n );\n\n return {\n ...(toolSelection === undefined ? {} : { toolSelection }),\n policyUsage: validatedPolicyUsage,\n prompt: Prompt.fromMessages(state.all),\n historyBefore: Prompt.fromMessages(state.before),\n committedTurns: state.committedTurns,\n usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls },\n ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }),\n ...(protectedContext === undefined ? {} : { protectedContext }),\n ...(ownerTerminated || pendingContextToolCallId === undefined\n ? {}\n : { pendingContextToolCallId }),\n };\n});\n\n/** Pure projection of one Run's durable recovery state from canonical records. */\nexport const projectRunJournal = Effect.fn(\"RunJournal.projectRunJournal\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n runId: RunId,\n ): Effect.Effect<RunJournalProjection, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), runId),\n);\n\n/**\n * Pure valid-prompt projection from canonical records: `UserInputRecorded` +\n * `ModelResponseRecorded` + complete `ToolCallSettled` batches → the deterministic model-visible\n * Prompt (plan §Coordinator flow step 3).\n */\nexport const promptFromCanonicalRecords = Effect.fn(\"RunJournal.promptFromCanonicalRecords\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n ): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), undefined).pipe(\n Effect.map((projection) => projection.prompt),\n ),\n);\n\n/** Everything one committed Turn contributes to its canonical batch. */\n/**\n * Staged usage is validated, never repaired: clamping negatives or truncating\n * fractions would under-record canonical usage, and NaN/Infinity must fail\n * typed instead of escaping as a record-construction defect (RUN-023).\n */\nconst validStagedUsage = (label: string, value: number): Effect.Effect<number, RunJournalError> =>\n Number.isSafeInteger(value) && value >= 0\n ? Effect.succeed(value)\n : Effect.fail(\n journalError(`Staged ${label} must be a non-negative safe integer, got ${String(value)}`),\n );\n\nexport interface TurnCommitInput {\n readonly toolOperations?: ModelResponseRecorded[\"toolOperations\"] | undefined;\n readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;\n readonly toolExposure?: Snapshot | undefined;\n readonly toolSelections?: ReadonlyMap<string, Selection> | undefined;\n readonly budgetRejectedCalls?: ReadonlySet<string>;\n readonly runId: RunId;\n /** Canonical (Run-relative, Attempt-independent) Turn number; must be positive. */\n readonly turn: number;\n readonly turnId: TurnId;\n /**\n * The Prompt messages this Turn appended to official history, in order, including the Turn's\n * Tool message when application Tools ran. Tool messages become `ToolCallSettled` records; the\n * remaining messages become the Turn's `ModelResponseRecorded.messages`.\n */\n readonly appended: ReadonlyArray<Prompt.Message>;\n readonly producerId: ProducerId;\n readonly deploymentId: DeploymentId;\n readonly createdAt: DateTime.Utc;\n /** Leading instruction/wake messages that stay canonical but are hidden from later Runs. */\n readonly runScopedPrefixLength?: number | undefined;\n /** Terminal output committed atomically with this Turn's final canonical batch. */\n readonly runCompletion?:\n | {\n readonly output: PersistedJson;\n readonly runDisposition?: PersistedJson | undefined;\n readonly finishReason?: \"budget-exhausted\" | undefined;\n readonly exhausted?: ExhaustedLimit | undefined;\n }\n | undefined;\n /** Known missing-accounting invocations staged before this canonical response. */\n readonly unobservedModelCalls?: number | undefined;\n /** Per-call provider usage staged by the engine's `noteTurnUsage` (RUN-023). */\n readonly usage?:\n | {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd?: number | undefined;\n readonly modelUsage?: ReadonlyArray<ModelCallUsage> | undefined;\n }\n | undefined;\n}\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodePrompt = Schema.encodeEffect(Prompt.Prompt);\nconst decodeModelUsage = Schema.decodeUnknownEffect(Schema.Array(ModelCallUsage));\n\nconst requireCanonicalTurn = (turn: number): Effect.Effect<void, RunJournalError> =>\n !Number.isInteger(turn) || turn <= 0\n ? Effect.fail(journalError(`Canonical turn number must be a positive integer: ${turn}`))\n : Effect.void;\n\ninterface SplitTurnMessages {\n readonly promptMessages: ReadonlyArray<Prompt.Message>;\n readonly toolParts: ReadonlyArray<Prompt.ToolResultPart>;\n}\n\nconst splitTurnMessages = (appended: ReadonlyArray<Prompt.Message>): SplitTurnMessages => {\n const promptMessages: Array<Prompt.Message> = [];\n const toolParts: Array<Prompt.ToolResultPart> = [];\n\n for (const message of appended) {\n if (message.role !== \"tool\") {\n promptMessages.push(message);\n continue;\n }\n for (const part of message.content) {\n if (part.type !== \"tool-result\") continue;\n toolParts.push(part);\n }\n }\n\n return { promptMessages, toolParts };\n};\n\nconst modelResponseRecord = Effect.fn(\"RunJournal.modelResponseRecord\")(function* (\n input: TurnCommitInput,\n promptMessages: ReadonlyArray<Prompt.Message>,\n): Effect.fn.Return<RecordEnvelope, RunJournalError | DigestError, Crypto.Crypto> {\n if (promptMessages.length === 0) {\n return yield* journalError(`Turn ${input.turn} appended no model-visible Prompt messages`);\n }\n const runScopedPrefixLength = input.runScopedPrefixLength;\n\n if (\n runScopedPrefixLength !== undefined &&\n (input.turn !== 1 ||\n !Number.isSafeInteger(runScopedPrefixLength) ||\n runScopedPrefixLength <= 0 ||\n runScopedPrefixLength >= promptMessages.length ||\n promptMessages\n .slice(0, runScopedPrefixLength)\n .some((message) => message.role !== \"system\" && message.role !== \"user\"))\n ) {\n return yield* journalError(\n \"Run-scoped Prompt provenance must identify a non-empty system/user prefix of Turn 1 before its assistant response\",\n );\n }\n\n const encodedMessages = yield* encodePrompt(Prompt.fromMessages([...promptMessages])).pipe(\n Effect.mapError((cause) => journalError(\"Turn Prompt messages failed to encode\", cause)),\n );\n\n const messages = yield* decodePersistedJson(encodedMessages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Turn Prompt messages exceed canonical persistence bounds\", cause),\n ),\n );\n\n const messagesDigest = yield* digestJson(messages);\n\n const modelUsage =\n input.usage?.modelUsage === undefined\n ? undefined\n : yield* decodeModelUsage(input.usage.modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage failed to decode\", cause)),\n );\n\n if (modelUsage !== undefined) {\n if (modelUsage.length === 0) {\n return yield* journalError(\"Turn model usage must contain at least one completed call\");\n }\n\n const summary = yield* summarizeModelUsage(modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage exceeds accounting bounds\", cause)),\n );\n\n if (\n input.usage === undefined ||\n input.usage.inputTokens !== summary.inputTokens.total ||\n input.usage.outputTokens !== summary.outputTokens.total ||\n (input.usage.costMicrousd ?? 0) !== summary.costMicrousd\n ) {\n return yield* journalError(\"Turn detailed and aggregate model usage disagree\");\n }\n }\n\n return RecordEnvelope.make({\n recordId: modelResponseRecordId(input.runId, input.turn),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ModelResponseRecorded.make({\n ...(input.toolOperations === undefined ? {} : { toolOperations: input.toolOperations }),\n ...(input.toolParameterRejections === undefined || input.toolParameterRejections.length === 0\n ? {}\n : { toolParameterRejections: input.toolParameterRejections }),\n ...(input.toolExposure === undefined ? {} : { toolExposure: input.toolExposure }),\n runId: input.runId,\n turnId: input.turnId,\n turn: input.turn,\n messages,\n messagesDigest,\n ...(runScopedPrefixLength === undefined ? {} : { runScopedPrefixLength }),\n ...(modelUsage === undefined ? {} : { modelUsage }),\n ...(input.unobservedModelCalls === undefined || input.unobservedModelCalls === 0\n ? {}\n : {\n unobservedModelCalls: yield* validStagedUsage(\n \"unobservedModelCalls\",\n input.unobservedModelCalls,\n ),\n }),\n ...(input.usage === undefined\n ? {}\n : {\n inputTokens: yield* validStagedUsage(\"inputTokens\", input.usage.inputTokens),\n outputTokens: yield* validStagedUsage(\"outputTokens\", input.usage.outputTokens),\n // Written only when non-zero: absent re-seeds as zero, so the\n // no-estimator case stays byte-identical to pre-cost histories.\n ...(input.usage.costMicrousd === undefined || input.usage.costMicrousd === 0\n ? {}\n : {\n costMicrousd: yield* validStagedUsage(\"costMicrousd\", input.usage.costMicrousd),\n }),\n }),\n }),\n });\n});\n\nconst toolSettledRecords = Effect.fn(\"RunJournal.toolSettledRecords\")(function* (\n input: TurnCommitInput,\n toolParts: ReadonlyArray<Prompt.ToolResultPart>,\n): Effect.fn.Return<Array<RecordEnvelope>, RunJournalError> {\n const toolRecords: Array<RecordEnvelope> = [];\n\n for (const part of toolParts) {\n const result = yield* decodePersistedJson(part.result).pipe(\n Effect.mapError((cause) =>\n journalError(`Tool result ${part.id} exceeds canonical persistence bounds`, cause),\n ),\n );\n\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(part.id),\n catch: (cause) => journalError(`Invalid Tool Call ID ${part.id}`, cause),\n });\n\n toolRecords.push(\n RecordEnvelope.make({\n recordId: toolCallSettledRecordId(input.runId, input.turn, toolCallId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ToolCallSettled.make({\n ...(input.toolSelections?.get(part.id) === undefined\n ? {}\n : { toolSelection: input.toolSelections.get(part.id) }),\n runId: input.runId,\n toolCallId,\n toolName: part.name,\n result,\n isFailure: part.isFailure,\n ...(input.budgetRejectedCalls?.has(part.id) === true ? { budgetRejected: true } : {}),\n }),\n }),\n );\n }\n\n return toolRecords;\n});\n\n/** Integrity of the original validated terminal values; never a current-code projection. */\nexport const runCompletionDigest = (\n completion: Pick<\n RunCompleted,\n \"runId\" | \"output\" | \"runDisposition\" | \"finishReason\" | \"exhausted\"\n >,\n) =>\n digestJson({\n runId: completion.runId,\n output: completion.output,\n runDisposition: completion.runDisposition ?? null,\n finishReason: completion.finishReason ?? null,\n exhausted: completion.exhausted ?? null,\n });\n\nconst runCompletionRecord = Effect.fn(\"RunJournal.runCompletionRecord\")(function* (\n input: TurnCommitInput,\n) {\n if (input.runCompletion === undefined) return undefined;\n const completion = { runId: input.runId, ...input.runCompletion };\n\n return RecordEnvelope.make({\n recordId: runCompletedRecordId(input.runId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: RunCompleted.make({\n ...completion,\n resultDigest: yield* runCompletionDigest(completion),\n }),\n });\n});\n\n/**\n * Pure per-Turn canonical batch builder (TurnCompleted seam fold, D6/D8): one\n * `ModelResponseRecorded` record plus one `ToolCallSettled` record per terminal Tool result, all\n * under the WP0-style deterministic identities, committed as ONE atomic batch. The same input\n * always yields byte-identical content, so an in-Attempt append retry is an honest batch replay.\n *\n * Phase 5 keeps this shape for Turns that declare no application Tool calls; their terminal\n * `RunCompleted` marker joins the response in this same atomic batch. Tool-declaring Turns split\n * into `turnResponseBatch` + `turnResultsBatch`.\n */\nexport const turnCanonicalBatch = Effect.fn(\"RunJournal.turnCanonicalBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages, toolParts } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const completionRecord = yield* runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [modelResponse, ...toolRecords]\n : [modelResponse, ...toolRecords, completionRecord],\n });\n});\n\n/**\n * Commit 1 of a tool-declaring Turn: the Turn's `ModelResponseRecorded` record, including\n * provider results retained in assistant content before application Tools execute.\n * — pending steering plus the assistant response with its declared tool calls — under batch\n * identity `turn-response:{runId}:{turn}`. Committing the response before preparation creates\n * the provably-safe durability §15 window (\"after model item commit, before tool preparation →\n * resume tool scheduling\"): a crash there resumes the declared batch with no model re-invocation\n * and no Unknown. Tool messages in `appended` are ignored; the record identity is the same\n * `model-response:{runId}:{turn}` as the single-batch shape, so record-id assertions and the\n * prompt projection are unchanged.\n */\nexport const turnResponseBatch = Effect.fn(\"RunJournal.turnResponseBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n\n return CanonicalBatch.make({\n batchId: turnResponseBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records: [modelResponse],\n });\n});\n\n/**\n * Commit 5 of a tool-declaring Turn (plan §2.1): the Turn's `ToolCallSettled` records in\n * declaration order under batch identity `turn-results:{runId}:{turn}` — the batch becomes\n * model-visible atomically. Non-tool messages in `appended` are ignored; a Turn without any\n * terminal Tool result has no results batch and fails typed.\n */\nexport const turnResultsBatch = Effect.fn(\"RunJournal.turnResultsBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { toolParts } = splitTurnMessages(input.appended);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const first = toolRecords[0];\n\n if (first === undefined) {\n return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`);\n }\n if (input.runCompletion !== undefined && toolRecords.length !== 1) {\n return yield* journalError(\"A terminal Tool completion requires exactly one settled result\");\n }\n const completionRecord = yield* runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnResultsBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [first, ...toolRecords.slice(1)]\n : [first, ...toolRecords.slice(1), completionRecord],\n });\n});\n"],"mappings":";;;;;;;;;;;AAiCA,MAAa,oBACX,SACW,KAAK,UAAU;CAAC,KAAK;CAAO,KAAK;CAAM,KAAK;AAAU,CAAC;;;;;;AAOpE,MAAa,uBACX,YACA,SACG;CACH,MAAM,qCAAqB,IAAI,IAAoB;CAEnD,IAAI,MAAM,kBAAkB,KAAA,GAAW,mBAAmB,IAAI,KAAK,OAAO,KAAK,aAAa;CAC5F,MAAM,4CAA4B,IAAI,IAAoB;CAC1D,MAAM,wCAAwB,IAAI,IAAoB;CAEtD,MAAM,eACJ,CAAC;CAEH,MAAM,wCAAwB,IAAI,IAAY;CAC9C,MAAM,2CAA2B,IAAI,IAAY;CAEjD,MAAM,8BAAc,IAAI,IAGtB;CAEF,MAAM,cAAyF,CAAC;CAEhG,OAAO;EACL,MAAM,aAA4C;GAChD,MAAM,UAAU,SAAS,OAAO;GAEhC,KACG,QAAQ,SAAS,kBAChB,QAAQ,SAAS,eACjB,QAAQ,SAAS,wBACnB,QAAQ,UAAU,KAAA,KAClB,CAAC,sBAAsB,IAAI,QAAQ,KAAK,GAExC,sBAAsB,IAAI,QAAQ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BAAmB,OAAO,SAAS;CAC9D,MAAM,QAAQ,YAAY;CAE1B,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,aAAa,QAAQ,MAAM,KAAK,wCAAwC;CAExF,IAAI,MAAM,kBAAkB,KAAA,KAAa,YAAY,WAAW,GAC9D,OAAO,OAAO,aAAa,gEAAgE;CAE7F,MAAM,mBAAmB,OAAO,oBAAoB,KAAK;CAEzD,OAAO,eAAe,KAAK;EACzB,SAAS,mBAAmB,MAAM,OAAO,MAAM,IAAI;EACnD,YAAY,MAAM;EAClB,SACE,qBAAqB,KAAA,IACjB,CAAC,OAAO,GAAG,YAAY,MAAM,CAAC,CAAC,IAC/B;GAAC;GAAO,GAAG,YAAY,MAAM,CAAC;GAAG;EAAgB;CACzD,CAAC;AACH,CAAC"}
|
|
@@ -3,7 +3,7 @@ import { a as Receipt, r as Principal } from "./Receipt-BAHyigAF.mjs";
|
|
|
3
3
|
import { r as Update } from "./AgentUpdates-DMJ-_xow.mjs";
|
|
4
4
|
import { t as AgentPolicy } from "./AgentPolicy-BqDoSXO6.mjs";
|
|
5
5
|
import { _ as Digest, h as DefinitionDigests } from "./Records-B5GFWCpn.mjs";
|
|
6
|
-
import "./Admin-
|
|
6
|
+
import "./Admin-Fx85KT-W.mjs";
|
|
7
7
|
import { t as ScheduleAuthorizationDecision } from "./Schedule-CtYREFnz.mjs";
|
|
8
8
|
import { Context, Effect, Schema } from "effect";
|
|
9
9
|
declare namespace Subscription_d_exports {
|
|
@@ -976,4 +976,4 @@ declare const subscriptionKeyString: (key: SubscriptionKey) => string;
|
|
|
976
976
|
declare const subscriptionDeliveryKeyString: (key: SubscriptionDeliveryKey) => string;
|
|
977
977
|
//#endregion
|
|
978
978
|
export { defaultSubscriptionLimits as A, SubscriptionScanCursors as C, SubscriptionStore as D, SubscriptionSourceError as E, subscriptionKeyString as M, SubscriptionStoreFailure as O, SubscriptionRetentionPolicy as S, SubscriptionSnapshot as T, SubscriptionKey as _, PreparedInput as a, SubscriptionRecord as b, SubscriptionAuthorizer as c, SubscriptionDelivery as d, SubscriptionDeliveryKey as f, SubscriptionFailpointError as g, SubscriptionFailpoint as h, EventSourceVersion as i, subscriptionDeliveryKeyString as j, Subscription_d_exports as k, SubscriptionChange as l, SubscriptionError as m, DeliveryChange as n, SourcePartition as o, SubscriptionDeliverySnapshot as p, EventAcknowledgement as r, SourceRecovery as s, AcceptedEvent as t, SubscriptionConfiguration as u, SubscriptionLimits as v, SubscriptionScope as w, SubscriptionRefusal as x, SubscriptionName as y };
|
|
979
|
-
//# sourceMappingURL=Subscription-
|
|
979
|
+
//# sourceMappingURL=Subscription-CCmHgOYM.d.mts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as AgentId } from "./Identifiers-CN2s30fF.mjs";
|
|
2
2
|
import { O as PersistedJson, h as DefinitionDigests } from "./Records-B5GFWCpn.mjs";
|
|
3
|
-
import { E as SubscriptionSourceError, b as SubscriptionRecord, i as EventSourceVersion, m as SubscriptionError, t as AcceptedEvent, u as SubscriptionConfiguration } from "./Subscription-
|
|
3
|
+
import { E as SubscriptionSourceError, b as SubscriptionRecord, i as EventSourceVersion, m as SubscriptionError, t as AcceptedEvent, u as SubscriptionConfiguration } from "./Subscription-CCmHgOYM.mjs";
|
|
4
4
|
import { Context, Effect, Schema, Scope } from "effect";
|
|
5
5
|
declare namespace SubscriptionInput_d_exports {
|
|
6
6
|
export { SubscriptionInputBinding, SubscriptionInputBindings, makeSubscriptionInputBinding, resolveSubscriptionInput };
|
|
@@ -38,4 +38,4 @@ declare const makeSubscriptionInputBinding: <Event extends Schema.Top, Parameter
|
|
|
38
38
|
}) => Effect.Effect<SubscriptionInputBinding, never, Exclude<R, Scope.Scope> | Exclude<Continuation["DecodingServices"], Scope.Scope> | Exclude<Continuation["EncodingServices"], Scope.Scope> | Exclude<Event["DecodingServices"], Scope.Scope> | Exclude<Input["EncodingServices"], Scope.Scope> | Exclude<Parameters["DecodingServices"], Scope.Scope>>;
|
|
39
39
|
//#endregion
|
|
40
40
|
export { resolveSubscriptionInput as a, makeSubscriptionInputBinding as i, SubscriptionInputBindings as n, SubscriptionInput_d_exports as r, SubscriptionInputBinding as t };
|
|
41
|
-
//# sourceMappingURL=SubscriptionInput-
|
|
41
|
+
//# sourceMappingURL=SubscriptionInput-BFJMhu4K.d.mts.map
|
package/dist/durable/Admin.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as renderRecoveryExplanation, S as recoveryDecisionMeaning, _ as RetryCommand, a as IntegrityCheck, b as obligationSeverityOf, c as IntegrityReport, d as ObligationReport, f as ObligationSeverity, g as RecoveryExplanation, h as RecoveryDisposition, i as ExplainedUnknownCall, l as ObligationBlockedOn, m as RECOVERY_DECISION_MEANINGS, n as ExplainedEvidence, o as IntegrityCheckName, p as ObligationThresholds, r as ExplainedSubmission, s as IntegrityCheckStatus, u as ObligationEntry, v as RetryRefusalReason, x as predictRecoveryDisposition, y as RetryRefused } from "../Admin-
|
|
1
|
+
import { C as renderRecoveryExplanation, S as recoveryDecisionMeaning, _ as RetryCommand, a as IntegrityCheck, b as obligationSeverityOf, c as IntegrityReport, d as ObligationReport, f as ObligationSeverity, g as RecoveryExplanation, h as RecoveryDisposition, i as ExplainedUnknownCall, l as ObligationBlockedOn, m as RECOVERY_DECISION_MEANINGS, n as ExplainedEvidence, o as IntegrityCheckName, p as ObligationThresholds, r as ExplainedSubmission, s as IntegrityCheckStatus, u as ObligationEntry, v as RetryRefusalReason, x as predictRecoveryDisposition, y as RetryRefused } from "../Admin-Fx85KT-W.mjs";
|
|
2
2
|
export { ExplainedEvidence, ExplainedSubmission, ExplainedUnknownCall, IntegrityCheck, IntegrityCheckName, IntegrityCheckStatus, IntegrityReport, ObligationBlockedOn, ObligationEntry, ObligationReport, ObligationSeverity, ObligationThresholds, RECOVERY_DECISION_MEANINGS, RecoveryDisposition, RecoveryExplanation, RetryCommand, RetryRefusalReason, RetryRefused, obligationSeverityOf, predictRecoveryDisposition, recoveryDecisionMeaning, renderRecoveryExplanation };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Aa as ResolvedBinding, Ca as AgentAttemptContext, Da as DurableWorkerBinding, Ea as DurableBindingFailure, Ma as compileRegistrations, Na as definitionDigestsEqual, Oa as ExecutableAgentBinding, Ta as BindingUnavailable, ja as compileBindingContracts, ka as ReplayVersions, wa as AgentRegistration } from "../Admin-
|
|
1
|
+
import { Aa as ResolvedBinding, Ca as AgentAttemptContext, Da as DurableWorkerBinding, Ea as DurableBindingFailure, Ma as compileRegistrations, Na as definitionDigestsEqual, Oa as ExecutableAgentBinding, Ta as BindingUnavailable, ja as compileBindingContracts, ka as ReplayVersions, wa as AgentRegistration } from "../Admin-Fx85KT-W.mjs";
|
|
2
2
|
export { type AgentAttemptContext, type AgentRegistration, BindingUnavailable, type DurableBindingFailure, DurableWorkerBinding, type ExecutableAgentBinding, type ReplayVersions, type ResolvedBinding, compileBindingContracts, compileRegistrations, definitionDigestsEqual };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ni as ThreadStore, vn as SubmissionLedger } from "../Admin-
|
|
1
|
+
import { ni as ThreadStore, vn as SubmissionLedger } from "../Admin-Fx85KT-W.mjs";
|
|
2
2
|
import { Crypto, Effect, Schema } from "effect";
|
|
3
3
|
//#region src/durable/Certification.d.ts
|
|
4
4
|
declare const CertifiedAdapterIdentity_base: Schema.Class<CertifiedAdapterIdentity, Schema.Struct<{
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { O as PersistedJson, l as CanonicalRecordEnvelope } from "../Records-B5GFWCpn.mjs";
|
|
2
2
|
import { ActivityProcessorKey, ActivityProcessorStore, ActivityStoreFailure, PreparedActivity } from "./ActivityStore.mjs";
|
|
3
3
|
import { t as DigestError } from "../Digest-U69rDHuO.mjs";
|
|
4
|
-
import { Gr as ThreadNotMaterialized, ii as ThreadStoreError, ni as ThreadStore } from "../Admin-
|
|
4
|
+
import { Gr as ThreadNotMaterialized, ii as ThreadStoreError, ni as ThreadStore } from "../Admin-Fx85KT-W.mjs";
|
|
5
5
|
import { Crypto, Effect, Schema, Scope } from "effect";
|
|
6
6
|
declare namespace CommittedActivity_d_exports {
|
|
7
7
|
export { ActivityPassLimits, ActivityPassResult, ActivityProcessingError, CommittedActivityProcessor, activityWorkId, processCommittedActivity };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { a as Receipt } from "../Receipt-BAHyigAF.mjs";
|
|
2
|
-
import { $n as DurableApprovalFailure, Cr as isolateRecovery, Dr as threadCreatedRecordId, Er as threadCreatedBatchId, Sr as childReservationIdFor, Tr as recoveryRepairRecordId, Xn as DurableAbortFailure, Yn as ApprovalSuspensionError, Zn as DurableAgentRuntime, _r as RecoveryBlocked, ar as DurableObserveOptions, br as RecoverySweepOptions, cr as DurableRetryFailure, dr as DurableSubmitAgent, er as DurableApprovalResolver, fr as DurableSubmitFailure, gr as DurableWorkerRequirements, hr as DurableWorkerFailure, ir as DurableObligationFailure, lr as DurableRuntimeConfig, mr as DurableVerifyFailure, nr as DurableAwaitFailure, or as DurableProgressFailure, pr as DurableSubmitOptions, rr as DurableExplainFailure, sr as DurableResolveFailure, tr as DurableApprovalSuspension, ur as DurableRuntimeConfigOptions, vr as RecoveryFailure, wr as recoveryRepairBatchId, xr as RecoverySweepResult, yr as RecoveryReport } from "../Admin-
|
|
2
|
+
import { $n as DurableApprovalFailure, Cr as isolateRecovery, Dr as threadCreatedRecordId, Er as threadCreatedBatchId, Sr as childReservationIdFor, Tr as recoveryRepairRecordId, Xn as DurableAbortFailure, Yn as ApprovalSuspensionError, Zn as DurableAgentRuntime, _r as RecoveryBlocked, ar as DurableObserveOptions, br as RecoverySweepOptions, cr as DurableRetryFailure, dr as DurableSubmitAgent, er as DurableApprovalResolver, fr as DurableSubmitFailure, gr as DurableWorkerRequirements, hr as DurableWorkerFailure, ir as DurableObligationFailure, lr as DurableRuntimeConfig, mr as DurableVerifyFailure, nr as DurableAwaitFailure, or as DurableProgressFailure, pr as DurableSubmitOptions, rr as DurableExplainFailure, sr as DurableResolveFailure, tr as DurableApprovalSuspension, ur as DurableRuntimeConfigOptions, vr as RecoveryFailure, wr as recoveryRepairBatchId, xr as RecoverySweepResult, yr as RecoveryReport } from "../Admin-Fx85KT-W.mjs";
|
|
3
3
|
export { ApprovalSuspensionError, DurableAbortFailure, DurableAgentRuntime, DurableApprovalFailure, DurableApprovalResolver, DurableApprovalSuspension, DurableAwaitFailure, DurableExplainFailure, DurableObligationFailure, DurableObserveOptions, DurableProgressFailure, DurableResolveFailure, DurableRetryFailure, DurableRuntimeConfig, DurableRuntimeConfigOptions, DurableSubmitAgent, DurableSubmitFailure, DurableSubmitOptions, DurableVerifyFailure, DurableWorkerFailure, DurableWorkerRequirements, Receipt, RecoveryBlocked, RecoveryFailure, RecoveryReport, RecoverySweepOptions, RecoverySweepResult, childReservationIdFor, isolateRecovery, recoveryRepairBatchId, recoveryRepairRecordId, threadCreatedBatchId, threadCreatedRecordId };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { Receipt } from "../core/Receipt.mjs";
|
|
2
|
-
import { a as DurableApprovalSuspension, c as RecoveryFailure, d as childReservationIdFor, f as isolateRecovery, g as threadCreatedRecordId, h as threadCreatedBatchId, i as DurableApprovalResolver, l as RecoveryReport, m as recoveryRepairRecordId, n as DurableAgentRuntime, o as DurableRuntimeConfig, p as recoveryRepairBatchId, s as RecoveryBlocked, t as ApprovalSuspensionError, u as RecoverySweepResult } from "../DurableAgentRuntime-
|
|
2
|
+
import { a as DurableApprovalSuspension, c as RecoveryFailure, d as childReservationIdFor, f as isolateRecovery, g as threadCreatedRecordId, h as threadCreatedBatchId, i as DurableApprovalResolver, l as RecoveryReport, m as recoveryRepairRecordId, n as DurableAgentRuntime, o as DurableRuntimeConfig, p as recoveryRepairBatchId, s as RecoveryBlocked, t as ApprovalSuspensionError, u as RecoverySweepResult } from "../DurableAgentRuntime-Bso5grIH.mjs";
|
|
3
3
|
export { ApprovalSuspensionError, DurableAgentRuntime, DurableApprovalResolver, DurableApprovalSuspension, DurableRuntimeConfig, Receipt, RecoveryBlocked, RecoveryFailure, RecoveryReport, RecoverySweepResult, childReservationIdFor, isolateRecovery, recoveryRepairBatchId, recoveryRepairRecordId, threadCreatedBatchId, threadCreatedRecordId };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as makeEventSource, i as NormalizedEvent, r as EventSources, t as EventSource } from "../EventSource-
|
|
1
|
+
import { a as makeEventSource, i as NormalizedEvent, r as EventSources, t as EventSource } from "../EventSource-DLT8oDK8.mjs";
|
|
2
2
|
export { EventSource, EventSources, NormalizedEvent, makeEventSource };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { r as Principal } from "../Receipt-BAHyigAF.mjs";
|
|
2
|
-
import "../Admin-
|
|
3
|
-
import { E as SubscriptionSourceError } from "../Subscription-
|
|
4
|
-
import { t as EventSource } from "../EventSource-
|
|
2
|
+
import "../Admin-Fx85KT-W.mjs";
|
|
3
|
+
import { E as SubscriptionSourceError } from "../Subscription-CCmHgOYM.mjs";
|
|
4
|
+
import { t as EventSource } from "../EventSource-DLT8oDK8.mjs";
|
|
5
5
|
import { SubscriptionFailure, SubscriptionIntake } from "./Subscriptions.mjs";
|
|
6
6
|
import { Context, Effect, Layer, Redacted, Schema } from "effect";
|
|
7
7
|
import { HttpClient } from "effect/unstable/http";
|