Open History to see the last commit
1import type {
2 OrchestrationV2ContextHandoff,
3 OrchestrationV2ProviderThread,
4} from "@t3tools/contracts";
5import type { ProviderAdapterV2HistoricalContext } from "./ProviderAdapter.ts";
6import * as Effect from "effect/Effect";
7import * as Schema from "effect/Schema";
8import { historyCost, renderHistory, selectHistory } from "./ContextHandoffBudget.ts";
9
10/** Persist before/after injection: an ambiguous pending delivery requires a fresh native thread. */
11export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextHandoffs")(
12 function* <InjectError, PersistError>(input: {
13 readonly handoffs: ReadonlyArray<OrchestrationV2ContextHandoff>;
14 readonly providerThread: OrchestrationV2ProviderThread;
15 readonly budget: number;
16 readonly deferInline?: boolean;
17 readonly alreadyDeliveredItemIds: ReadonlySet<string>;
18 readonly inject?: (
19 history: ProviderAdapterV2HistoricalContext,
20 ) => Effect.Effect<boolean, InjectError>;
21 readonly persist: (handoff: OrchestrationV2ContextHandoff) => Effect.Effect<void, PersistError>;
22 }) {
23 const nativeThreadId = input.providerThread.nativeThreadRef?.nativeId ?? undefined;
24 const pending = input.handoffs.filter(
25 (handoff) =>
26 nativeThreadId === undefined ||
27 handoff.delivery?.nativeThreadId !== nativeThreadId ||
28 handoff.delivery.status === "pending",
29 );
30 if (pending.length === 0 || (input.deferInline && input.inject === undefined))
31 return { context: "", delivered: Effect.void };
32 let coverage = pending
33 .map(
34 (handoff) =>
35 `Context handoff (${handoff.strategy === "fork_delta_summary" ? "merge_back / fork_delta_summary" : handoff.strategy}):\n${
36 handoff.history?.coverage ??
37 `From thread ${handoff.threadId}, runs ${handoff.coveredRunOrdinals.from}-${handoff.coveredRunOrdinals.to}. Recover history with t3_thread_read, view=activity; paginate with afterPosition, and use itemId/textOffset for long items.`
38 }`,
39 )
40 .join("\n");
41 // Repeated failures can accumulate many recovery markers. Keep a single
42 // thread-level entry point when detailed coverage would crowd out history;
43 // its activity includes the original handoff/fork source references.
44 if (historyCost([], coverage) > Math.min(4_000, input.budget / 2)) {
45 const strategies = Array.from(new Set(pending.map((handoff) => handoff.strategy)));
46 coverage = `Context handoff (${strategies.join(", ")}). ${pending.length} handoff records; detailed coverage references omitted. Recover history with t3_thread_read({threadId:"${input.providerThread.appThreadId ?? pending[0]!.threadId}",view:"activity",limit:20,maxCharsPerItem:4000}); paginate with afterPosition=nextPosition. Follow fork/handoff source references in activity. For long items use itemId and textOffset=nextTextOffset until null.`;
47 }
48 const seen = new Set(input.alreadyDeliveredItemIds);
49 const messages = pending
50 .flatMap((handoff) => handoff.history?.messages ?? [])
51 .filter((message) => {
52 if (seen.has(message.itemId)) return false;
53 seen.add(message.itemId);
54 return true;
55 });
56 // Old preview handoffs remain readable. Their preformatted context is included
57 // as a whole when it fits, otherwise the coverage marker points to retrieval.
58 const oldContext = pending
59 .filter((handoff) => handoff.history === undefined)
60 .map((handoff) => handoff.summaryText)
61 .join("\n\n");
62 const fullCoverage =
63 oldContext && historyCost([], `${coverage}\n${oldContext}`) + 512 <= input.budget
64 ? `${coverage}\n${oldContext}`
65 : coverage;
66 const selected = selectHistory({
67 messages,
68 coverage: fullCoverage,
69 omittedItems: pending.reduce((sum, handoff) => sum + (handoff.history?.omittedItems ?? 0), 0),
70 budget: input.budget,
71 });
72 if (historyCost(selected.messages, selected.context) > input.budget) {
73 if (input.deferInline) return { context: "", delivered: Effect.void };
74 return yield* new ContextHandoffBudgetError();
75 }
76 const omittedItemIds = new Set(selected.omittedItemIds);
77 const persist = (status: "pending" | "injected" | "inline") =>
78 Effect.forEach(
79 pending,
80 (handoff) =>
81 input.persist({
82 ...handoff,
83 ...(nativeThreadId === undefined
84 ? {}
85 : {
86 delivery: {
87 nativeThreadId,
88 status,
89 omittedItemIds: [
90 ...(handoff.history?.omittedItemIds ?? []),
91 ...(handoff.history?.messages ?? [])
92 .filter((message) => omittedItemIds.has(message.itemId))
93 .map((message) => message.itemId),
94 ],
95 itemIds: selected.messages
96 .filter((message) =>
97 handoff.history?.messages.some(
98 (candidate) => candidate.itemId === message.itemId,
99 ),
100 )
101 .map((message) => message.itemId),
102 },
103 }),
104 }),
105 { discard: true },
106 );
107 if (input.inject !== undefined && nativeThreadId !== undefined) {
108 if (
109 pending.some(
110 (handoff) =>
111 handoff.delivery?.nativeThreadId === nativeThreadId &&
112 handoff.delivery.status === "pending",
113 )
114 ) {
115 return yield* new ContextHandoffDeliveryUncertainError();
116 }
117 yield* persist("pending");
118 const injected = yield* input.inject({
119 messages: selected.messages,
120 context: selected.context,
121 });
122 if (injected) {
123 yield* persist("injected");
124 return { context: "", delivered: Effect.void };
125 }
126 } else {
127 // Text-only delivery can also be accepted before a connection drops.
128 yield* persist("pending");
129 }
130 if (input.deferInline) {
131 // Compaction APIs cannot accept an inline transcript. Keep it available
132 // for the next ordinary turn when native injection is unsupported.
133 yield* Effect.forEach(pending, input.persist, { discard: true });
134 return { context: "", delivered: Effect.void };
135 }
136 return {
137 context: renderHistory(selected.messages, selected.context),
138 delivered: persist("inline"),
139 };
140 },
141);
142
143export class ContextHandoffBudgetError extends Schema.TaggedError<ContextHandoffBudgetError>()(
144 "ContextHandoffBudgetError",
145 {},
146) {
147 override get message() {
148 return "Insufficient context allowance for the provider handoff. Compact the target conversation or use a larger-context model; the current request has not been truncated.";
149 }
150}
151export class ContextHandoffDeliveryUncertainError extends Schema.TaggedError<ContextHandoffDeliveryUncertainError>()(
152 "ContextHandoffDeliveryUncertainError",
153 {},
154) {
155 override get message() {
156 return "Historical context delivery is uncertain; replace the native thread before retrying.";
157 }
158}