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

ContextHandoffDelivery.ts

166 lines7.5 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// A first word with a second slash is a path, not a command.
16const SLASH_COMMAND = /^\s*\/[^\s/]+(?:\s|$)/u;
17​
18/** Providers only run a native command that opens the prompt, so its turn defers inline context to the next one. */
19export const isSlashCommandMessage = (message: {
20 readonly role: string;
21 readonly text: string;
22}): boolean => message.role === "user" && SLASH_COMMAND.test(message.text);
23​
24/** The provider prompt for a turn that carries inline context ahead of the user's text. */
25export const withInlineContext = (context: string, userText: string): string =>
26 context === "" ? userText : `${context}\n\nUser message:\n${userText}`;
27​
28/** Persist around injection; ambiguous delivery requires a fresh native thread. Call unsent if refused before prompt consumption. */
29export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextHandoffs")(
30 function* <InjectError = never, PersistError = never, BudgetError = never>(input: {
31 readonly handoffs: ReadonlyArray<OrchestrationV2ContextHandoff>;
32 readonly providerThread: OrchestrationV2ProviderThread;
33 readonly budget: number | Effect.Effect<number, BudgetError>;
34 readonly deferInline?: boolean;
35 readonly alreadyDeliveredItemIds: ReadonlySet<string>;
36 readonly inject?: (
37 history: ProviderAdapter.ProviderAdapterV2HistoricalContext,
38 ) => Effect.Effect<boolean, InjectError>;
39 readonly persist: (handoff: OrchestrationV2ContextHandoff) => Effect.Effect<void, PersistError>;
40 }) {
41 const nativeThreadId = input.providerThread.nativeThreadRef?.nativeId ?? undefined;
42 const pending = input.handoffs.filter(
43 (handoff) =>
44 nativeThreadId === undefined ||
45 handoff.delivery?.nativeThreadId !== nativeThreadId ||
46 handoff.delivery.status === "pending",
47 );
48 if (pending.length === 0 || (input.deferInline && input.inject === undefined))
49 return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] };
50 const budget = typeof input.budget === "number" ? input.budget : yield* input.budget;
51 let coverage = pending
52 .map(
53 (handoff) =>
54 `Context handoff (${handoff.strategy === "fork_delta_summary" ? "merge_back / fork_delta_summary" : handoff.strategy}):\n${
55 handoff.history?.coverage ??
56 `From thread ${handoff.threadId}, runs ${handoff.coveredRunOrdinals.from}-${handoff.coveredRunOrdinals.to}. Recover history with t3_thread_read, view=activity, afterPosition=-1; paginate with afterPosition=nextPosition, and use itemId/textOffset for long items.`
57 }`,
58 )
59 .join("\n");
60 if (historyCost([], coverage) > Math.min(4_000, budget / 2)) {
61 const strategies = Array.from(new Set(pending.map((handoff) => handoff.strategy)));
62 coverage = `Context handoff (${strategies.join(", ")}). ${pending.length} handoff records; detailed coverage references omitted. Recover an omitted item only when the request needs it, with t3_thread_read({threadId:"${input.providerThread.appThreadId ?? pending[0]!.threadId}",view:"activity",itemId:"<omitted item ID>",maxCharsPerItem:4000}); continue long text with textOffset=nextTextOffset until null. Follow fork/handoff source references in activity. Items included below need no read.`;
63 }
64 const seen = new Set(input.alreadyDeliveredItemIds);
65 const messages = pending
66 .flatMap((handoff) => handoff.history?.messages ?? [])
67 .filter((message) => {
68 if (seen.has(message.itemId)) return false;
69 seen.add(message.itemId);
70 return true;
71 });
72 const oldContext = pending
73 .filter((handoff) => handoff.history === undefined)
74 .map((handoff) => handoff.summaryText)
75 .join("\n\n");
76 const fullCoverage =
77 oldContext && historyCost([], `${coverage}\n${oldContext}`) + 512 <= budget
78 ? `${coverage}\n${oldContext}`
79 : coverage;
80 const selected = selectHistory({
81 messages,
82 coverage: fullCoverage,
83 omittedItems: pending.reduce((sum, handoff) => sum + (handoff.history?.omittedItems ?? 0), 0),
84 omittedItemIds: pending.flatMap((handoff) => handoff.history?.omittedItemIds ?? []),
85 budget,
86 });
87 if (historyCost(selected.messages, selected.context) > budget) {
88 if (input.deferInline)
89 return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] };
90 return yield* new ContextHandoffBudgetError();
91 }
92 const omittedItemIds = new Set(selected.omittedItemIds);
93 const persist = (status: "pending" | "injected" | "inline") =>
94 Effect.forEach(
95 pending,
96 (handoff) =>
97 input.persist({
98 ...handoff,
99 ...(nativeThreadId === undefined
100 ? {}
101 : {
102 delivery: {
103 nativeThreadId,
104 status,
105 omittedItemIds: [
106 ...(handoff.history?.omittedItemIds ?? []),
107 ...(handoff.history?.messages ?? [])
108 .filter((message) => omittedItemIds.has(message.itemId))
109 .map((message) => message.itemId),
110 ],
111 itemIds: selected.messages
112 .filter((message) =>
113 handoff.history?.messages.some(
114 (candidate) => candidate.itemId === message.itemId,
115 ),
116 )
117 .map((message) => message.itemId),
118 },
119 }),
120 }),
121 { discard: true },
122 );
123 if (input.inject !== undefined && nativeThreadId !== undefined) {
124 if (
125 pending.some(
126 (handoff) =>
127 handoff.delivery?.nativeThreadId === nativeThreadId &&
128 handoff.delivery.status === "pending",
129 )
130 ) {
131 return yield* new ContextHandoffDeliveryUncertainError();
132 }
133 yield* persist("pending");
134 const injected = yield* input.inject({
135 messages: selected.messages,
136 context: selected.context,
137 });
138 if (injected) {
139 yield* persist("injected");
140 return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] };
141 }
142 } else {
143 yield* persist("pending");
144 }
145 if (input.deferInline) {
146 // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported.
147 yield* Effect.forEach(pending, input.persist, { discard: true });
148 return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] };
149 }
150 return {
151 context: renderHistory(selected.messages, selected.context),
152 delivered: persist("inline"),
153 unsent: Effect.forEach(pending, input.persist, { discard: true }),
154 inlineHandoffs: pending,
155 };
156 },
157);
158​
159export class ContextHandoffDeliveryUncertainError extends Schema.TaggedError<ContextHandoffDeliveryUncertainError>()(
160 "ContextHandoffDeliveryUncertainError",
161 {},
162) {
163 override get message() {
164 return "Historical context delivery is uncertain; replace the native thread before retrying.";
165 }