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

ContextHandoffDelivery.ts

150 lines6.6 KB

1import type {
2 OrchestrationV2ContextHandoff,
3 OrchestrationV2ProviderThread,
4} from "@t3tools/contracts";
5import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
6import { ContextHandoffBudgetError } from "@t3tools/provider-core/server/failure";
7import * as Effect from "effect/Effect";
8import * as Schema from "effect/Schema";
9import {
10 historyCost,
11 renderHistory,
12 selectHistory,
13} from "@t3tools/provider-core/server/handoffBudget";
14​
15/** Persist around injection; ambiguous delivery requires a fresh native thread. Call unsent if refused before prompt consumption. */
16export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextHandoffs")(
17 function* <InjectError = never, PersistError = never, BudgetError = never>(input: {
18 readonly handoffs: ReadonlyArray<OrchestrationV2ContextHandoff>;
19 readonly providerThread: OrchestrationV2ProviderThread;
20 readonly budget: number | Effect.Effect<number, BudgetError>;
21 readonly deferInline?: boolean;
22 readonly alreadyDeliveredItemIds: ReadonlySet<string>;
23 readonly inject?: (
24 history: ProviderAdapter.ProviderAdapterV2HistoricalContext,
25 ) => Effect.Effect<boolean, InjectError>;
26 readonly persist: (handoff: OrchestrationV2ContextHandoff) => Effect.Effect<void, PersistError>;
27 }) {
28 const nativeThreadId = input.providerThread.nativeThreadRef?.nativeId ?? undefined;
29 const pending = input.handoffs.filter(
30 (handoff) =>
31 nativeThreadId === undefined ||
32 handoff.delivery?.nativeThreadId !== nativeThreadId ||
33 handoff.delivery.status === "pending",
34 );
35 if (pending.length === 0 || (input.deferInline && input.inject === undefined))
36 return { context: "", delivered: Effect.void, unsent: Effect.void };
37 const budget = typeof input.budget === "number" ? input.budget : yield* input.budget;
38 let coverage = pending
39 .map(
40 (handoff) =>
41 `Context handoff (${handoff.strategy === "fork_delta_summary" ? "merge_back / fork_delta_summary" : handoff.strategy}):\n${
42 handoff.history?.coverage ??
43 `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.`
44 }`,
45 )
46 .join("\n");
47 if (historyCost([], coverage) > Math.min(4_000, budget / 2)) {
48 const strategies = Array.from(new Set(pending.map((handoff) => handoff.strategy)));
49 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.`;
50 }
51 const seen = new Set(input.alreadyDeliveredItemIds);
52 const messages = pending
53 .flatMap((handoff) => handoff.history?.messages ?? [])
54 .filter((message) => {
55 if (seen.has(message.itemId)) return false;
56 seen.add(message.itemId);
57 return true;
58 });
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, unsent: 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, unsent: Effect.void };
126 }
127 } else {
128 yield* persist("pending");
129 }
130 if (input.deferInline) {
131 // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported.
132 yield* Effect.forEach(pending, input.persist, { discard: true });
133 return { context: "", delivered: Effect.void, unsent: Effect.void };
134 }
135 return {
136 context: renderHistory(selected.messages, selected.context),
137 delivered: persist("inline"),
138 unsent: Effect.forEach(pending, input.persist, { discard: true }),
139 };
140 },
141);
142​
143export class ContextHandoffDeliveryUncertainError extends Schema.TaggedError<ContextHandoffDeliveryUncertainError>()(
144 "ContextHandoffDeliveryUncertainError",
145 {},
146) {
147 override get message() {
148 return "Historical context delivery is uncertain; replace the native thread before retrying.";
149 }