Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ContextHandoffDelivery.ts

159 lines7.1 KB

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 = never, PersistError = never, BudgetError = never>(input: {
13 readonly handoffs: ReadonlyArray<OrchestrationV2ContextHandoff>;
14 readonly providerThread: OrchestrationV2ProviderThread;
15 readonly budget: number | Effect.Effect<number, BudgetError>;
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 const budget = typeof input.budget === "number" ? input.budget : yield* input.budget;
33 let coverage = pending
34 .map(
35 (handoff) =>
36 `Context handoff (${handoff.strategy === "fork_delta_summary" ? "merge_back / fork_delta_summary" : handoff.strategy}):\n${
37 handoff.history?.coverage ??
38 `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.`
39 }`,
40 )
41 .join("\n");
42 // Repeated failures can accumulate many recovery markers. Keep a single
43 // thread-level entry point when detailed coverage would crowd out history;
44 // its activity includes the original handoff/fork source references.
45 if (historyCost([], coverage) > Math.min(4_000, budget / 2)) {
46 const strategies = Array.from(new Set(pending.map((handoff) => handoff.strategy)));
47 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.`;
48 }
49 const seen = new Set(input.alreadyDeliveredItemIds);
50 const messages = pending
51 .flatMap((handoff) => handoff.history?.messages ?? [])
52 .filter((message) => {
53 if (seen.has(message.itemId)) return false;
54 seen.add(message.itemId);
55 return true;
56 });
57 // Old preview handoffs remain readable. Their preformatted context is included
58 // as a whole when it fits, otherwise the coverage marker points to retrieval.
59 const oldContext = pending
60 .filter((handoff) => handoff.history === undefined)
61 .map((handoff) => handoff.summaryText)
62 .join("\n\n");
63 const fullCoverage =
64 oldContext && historyCost([], `${coverage}\n${oldContext}`) + 512 <= budget
65 ? `${coverage}\n${oldContext}`
66 : coverage;
67 const selected = selectHistory({
68 messages,
69 coverage: fullCoverage,
70 omittedItems: pending.reduce((sum, handoff) => sum + (handoff.history?.omittedItems ?? 0), 0),
71 budget,
72 });
73 if (historyCost(selected.messages, selected.context) > budget) {
74 if (input.deferInline) return { context: "", delivered: Effect.void };
75 return yield* new ContextHandoffBudgetError();
76 }
77 const omittedItemIds = new Set(selected.omittedItemIds);
78 const persist = (status: "pending" | "injected" | "inline") =>
79 Effect.forEach(
80 pending,
81 (handoff) =>
82 input.persist({
83 ...handoff,
84 ...(nativeThreadId === undefined
85 ? {}
86 : {
87 delivery: {
88 nativeThreadId,
89 status,
90 omittedItemIds: [
91 ...(handoff.history?.omittedItemIds ?? []),
92 ...(handoff.history?.messages ?? [])
93 .filter((message) => omittedItemIds.has(message.itemId))
94 .map((message) => message.itemId),
95 ],
96 itemIds: selected.messages
97 .filter((message) =>
98 handoff.history?.messages.some(
99 (candidate) => candidate.itemId === message.itemId,
100 ),
101 )
102 .map((message) => message.itemId),
103 },
104 }),
105 }),
106 { discard: true },
107 );
108 if (input.inject !== undefined && nativeThreadId !== undefined) {
109 if (
110 pending.some(
111 (handoff) =>
112 handoff.delivery?.nativeThreadId === nativeThreadId &&
113 handoff.delivery.status === "pending",
114 )
115 ) {
116 return yield* new ContextHandoffDeliveryUncertainError();
117 }
118 yield* persist("pending");
119 const injected = yield* input.inject({
120 messages: selected.messages,
121 context: selected.context,
122 });
123 if (injected) {
124 yield* persist("injected");
125 return { context: "", delivered: Effect.void };
126 }
127 } else {
128 // Text-only delivery can also be accepted before a connection drops.
129 yield* persist("pending");
130 }
131 if (input.deferInline) {
132 // Compaction APIs cannot accept an inline transcript. Keep it available
133 // for the next ordinary turn when native injection is unsupported.
134 yield* Effect.forEach(pending, input.persist, { discard: true });
135 return { context: "", delivered: Effect.void };
136 }
137 return {
138 context: renderHistory(selected.messages, selected.context),
139 delivered: persist("inline"),
140 };
141 },
142);
143​
144export class ContextHandoffBudgetError extends Schema.TaggedError<ContextHandoffBudgetError>()(
145 "ContextHandoffBudgetError",
146 {},
147) {
148 override get message() {
149 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.";
150 }
152export class ContextHandoffDeliveryUncertainError extends Schema.TaggedError<ContextHandoffDeliveryUncertainError>()(
153 "ContextHandoffDeliveryUncertainError",
154 {},
155) {
156 override get message() {
157 return "Historical context delivery is uncertain; replace the native thread before retrying.";
158 }