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

ContextHandoffDelivery.ts

154 lines6.8 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/** The provider prompt for a turn that carries inline context ahead of the user's text. */
16export const withInlineContext = (context: string, userText: string): string =>
17 context === "" ? userText : `${context}\n\nUser message:\n${userText}`;
18​
19/** Persist around injection; ambiguous delivery requires a fresh native thread. Call unsent if refused before prompt consumption. */
20export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextHandoffs")(
21 function* <InjectError = never, PersistError = never, BudgetError = never>(input: {
22 readonly handoffs: ReadonlyArray<OrchestrationV2ContextHandoff>;
23 readonly providerThread: OrchestrationV2ProviderThread;
24 readonly budget: number | Effect.Effect<number, BudgetError>;
25 readonly deferInline?: boolean;
26 readonly alreadyDeliveredItemIds: ReadonlySet<string>;
27 readonly inject?: (
28 history: ProviderAdapter.ProviderAdapterV2HistoricalContext,
29 ) => Effect.Effect<boolean, InjectError>;
30 readonly persist: (handoff: OrchestrationV2ContextHandoff) => Effect.Effect<void, PersistError>;
31 }) {
32 const nativeThreadId = input.providerThread.nativeThreadRef?.nativeId ?? undefined;
33 const pending = input.handoffs.filter(
34 (handoff) =>
35 nativeThreadId === undefined ||
36 handoff.delivery?.nativeThreadId !== nativeThreadId ||
37 handoff.delivery.status === "pending",
38 );
39 if (pending.length === 0 || (input.deferInline && input.inject === undefined))
40 return { context: "", delivered: Effect.void, unsent: Effect.void };
41 const budget = typeof input.budget === "number" ? input.budget : yield* input.budget;
42 let coverage = pending
43 .map(
44 (handoff) =>
45 `Context handoff (${handoff.strategy === "fork_delta_summary" ? "merge_back / fork_delta_summary" : handoff.strategy}):\n${
46 handoff.history?.coverage ??
47 `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.`
48 }`,
49 )
50 .join("\n");
51 if (historyCost([], coverage) > Math.min(4_000, budget / 2)) {
52 const strategies = Array.from(new Set(pending.map((handoff) => handoff.strategy)));
53 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.`;
54 }
55 const seen = new Set(input.alreadyDeliveredItemIds);
56 const messages = pending
57 .flatMap((handoff) => handoff.history?.messages ?? [])
58 .filter((message) => {
59 if (seen.has(message.itemId)) return false;
60 seen.add(message.itemId);
61 return true;
62 });
63 const oldContext = pending
64 .filter((handoff) => handoff.history === undefined)
65 .map((handoff) => handoff.summaryText)
66 .join("\n\n");
67 const fullCoverage =
68 oldContext && historyCost([], `${coverage}\n${oldContext}`) + 512 <= budget
69 ? `${coverage}\n${oldContext}`
70 : coverage;
71 const selected = selectHistory({
72 messages,
73 coverage: fullCoverage,
74 omittedItems: pending.reduce((sum, handoff) => sum + (handoff.history?.omittedItems ?? 0), 0),
75 budget,
76 });
77 if (historyCost(selected.messages, selected.context) > budget) {
78 if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void };
79 return yield* new ContextHandoffBudgetError();
80 }
81 const omittedItemIds = new Set(selected.omittedItemIds);
82 const persist = (status: "pending" | "injected" | "inline") =>
83 Effect.forEach(
84 pending,
85 (handoff) =>
86 input.persist({
87 ...handoff,
88 ...(nativeThreadId === undefined
89 ? {}
90 : {
91 delivery: {
92 nativeThreadId,
93 status,
94 omittedItemIds: [
95 ...(handoff.history?.omittedItemIds ?? []),
96 ...(handoff.history?.messages ?? [])
97 .filter((message) => omittedItemIds.has(message.itemId))
98 .map((message) => message.itemId),
99 ],
100 itemIds: selected.messages
101 .filter((message) =>
102 handoff.history?.messages.some(
103 (candidate) => candidate.itemId === message.itemId,
104 ),
105 )
106 .map((message) => message.itemId),
107 },
108 }),
109 }),
110 { discard: true },
111 );
112 if (input.inject !== undefined && nativeThreadId !== undefined) {
113 if (
114 pending.some(
115 (handoff) =>
116 handoff.delivery?.nativeThreadId === nativeThreadId &&
117 handoff.delivery.status === "pending",
118 )
119 ) {
120 return yield* new ContextHandoffDeliveryUncertainError();
121 }
122 yield* persist("pending");
123 const injected = yield* input.inject({
124 messages: selected.messages,
125 context: selected.context,
126 });
127 if (injected) {
128 yield* persist("injected");
129 return { context: "", delivered: Effect.void, unsent: Effect.void };
130 }
131 } else {
132 yield* persist("pending");
133 }
134 if (input.deferInline) {
135 // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported.
136 yield* Effect.forEach(pending, input.persist, { discard: true });
137 return { context: "", delivered: Effect.void, unsent: Effect.void };
138 }
139 return {
140 context: renderHistory(selected.messages, selected.context),
141 delivered: persist("inline"),
142 unsent: Effect.forEach(pending, input.persist, { discard: true }),
143 };
144 },
145);
146​
147export class ContextHandoffDeliveryUncertainError extends Schema.TaggedError<ContextHandoffDeliveryUncertainError>()(
148 "ContextHandoffDeliveryUncertainError",
149 {},
150) {
151 override get message() {
152 return "Historical context delivery is uncertain; replace the native thread before retrying.";
153 }