Open History to see the last commit
1import {
2 type ChatAttachment,
3 CommandId,
4 type OrchestrationV2Command,
5 OrchestrationV2ProviderCapabilities,
6 type OrchestrationV2GoalCommand,
7 type OrchestrationV2ProviderGoalStatus,
8 type OrchestrationV2Run,
9 OrchestrationV2ThreadProjection,
10 ProviderInstanceId,
11 ThreadId,
12} from "@t3tools/contracts";
13import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
14import * as Context from "effect/Context";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Schema from "effect/Schema";
18
19export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]);
20export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type;
21
22export const ForkExecutionPolicyV2 = Schema.Literals(["native_fork", "portable_context"]);
23export type ForkExecutionPolicyV2 = typeof ForkExecutionPolicyV2.Type;
24
25export const CommandPolicyCapability = Schema.Literals([
26 "queued_messages",
27 "active_steering",
28 "interrupt",
29 "interrupt_restart_steering",
30 "native_fork",
31 "fork_from_turn",
32 "rollback",
33 "rollback_snapshot",
34 "context_handoff",
35 "strong_terminal_status",
36]);
37export type CommandPolicyCapability = typeof CommandPolicyCapability.Type;
38
39export class CommandPolicyCapabilityUnsupportedError extends Schema.TaggedError<CommandPolicyCapabilityUnsupportedError>()(
40 "CommandPolicyCapabilityUnsupportedError",
41 {
42 commandId: CommandId,
43 threadId: ThreadId,
44 providerInstanceId: ProviderInstanceId,
45 capability: CommandPolicyCapability,
46 detail: Schema.String,
47 },
48) {
49 override get message(): string {
50 return `${this.providerInstanceId} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`;
51 }
52}
53
54export const CommandPolicyV2Error = Schema.Union([CommandPolicyCapabilityUnsupportedError]);
55export type CommandPolicyV2Error = typeof CommandPolicyV2Error.Type;
56
57type MessageDispatchMode = Extract<
58 OrchestrationV2Command,
59 { readonly type: "message.dispatch" }
60>["dispatchMode"];
61
62export function isNativeMaintenanceCommand(message: {
63 readonly text: string;
64 readonly attachments: ReadonlyArray<ChatAttachment>;
65 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
66}): boolean {
67 return (
68 message.attachments.length === 0 &&
69 ["/compact", "/logout"].includes(message.text.trim().toLowerCase())
70 );
71}
72
73/**
74 * A goal command sent into active work stops that work when it starts or
75 * replaces goal work, or ends a goal that is driving the run.
76 */
77export function goalCommandStopsActiveRun(
78 command: OrchestrationV2GoalCommand,
79 goalStatus: OrchestrationV2ProviderGoalStatus | null,
80): boolean {
81 switch (command.type) {
82 case "set":
83 case "resume":
84 return true;
85 case "clear":
86 case "pause":
87 return goalStatus === "active";
88 case "show":
89 return false;
90 }
91}
92
93export function resolveMessageDispatchIntent(
94 projection: OrchestrationV2ThreadProjection,
95 requestedMode: MessageDispatchMode,
96 deliveryIntent?: "auto" | "steer" | "restart",
97): MessageDispatchMode {
98 const mode = resolveDeliveryIntent(projection, requestedMode, deliveryIntent);
99 if (mode.type !== "steer_active") return mode;
100 // Compaction and sign-out cannot accept steers; queue follow-ups.
101 const target = projection.runs.find((run) => run.id === mode.targetRunId);
102 const targetMessage = projection.messages.find((message) => message.id === target?.userMessageId);
103 if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) {
104 return { type: "queue_after_active" };
105 }
106 // A provider that can neither steer nor restart its turn takes the message after the turn.
107 const turns =
108 target === undefined || !isActiveRun(target)
109 ? undefined
110 : providerTurnCapabilities(projection, target);
111 return turns !== undefined && !turns.supportsActiveSteering && providerSwitchWaitsForTurn(turns)
112 ? { type: "queue_after_active" }
113 : mode;
114}
115
116/** A run that still owns the thread's provider turn. */
117export function isActiveRun(run: OrchestrationV2Run): boolean {
118 return (
119 run.status === "preparing" ||
120 run.status === "starting" ||
121 run.status === "running" ||
122 run.status === "waiting"
123 );
124}
125
126/**
127 * Providers that key forks on native turn ids can only fork a busy source from a turn with one;
128 * a synthetic or missing boundary would fork the live conversation, including the running turn.
129 */
130export function canForkBusySourceNatively(
131 capabilities: OrchestrationV2ProviderCapabilities,
132 hasNativeTurnBoundary: boolean,
133): boolean {
134 return (
135 capabilities.threads.canForkWhileSourceRunning === true &&
136 (hasNativeTurnBoundary || !capabilities.turns.exposesNativeTurnId)
137 );
138}
139
140/** The run a follow-up to a finished child binds to: the latest active one, else the last that ran. */
141export function followUpOwnerRun(
142 runs: ReadonlyArray<OrchestrationV2Run>,
143): OrchestrationV2Run | null {
144 return (
145 runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ?? latestExecutedRun(runs)
146 );
147}
148
149/** A provider that cannot restart its turn for new input runs a provider switch after the turn. */
150export function providerSwitchWaitsForTurn(
151 turns: OrchestrationV2ProviderCapabilities["turns"],
152): boolean {
153 return (
154 turns.supportsQueuedMessages &&
155 !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart)
156 );
157}
158
159export function providerTurnCapabilities(
160 projection: OrchestrationV2ThreadProjection,
161 run: OrchestrationV2Run,
162) {
163 const providerThread = projection.providerThreads.find(
164 (candidate) => candidate.id === run.providerThreadId,
165 );
166 const providerSession =
167 providerThread?.providerSessionId == null
168 ? undefined
169 : projection.providerSessions.find(
170 (candidate) => candidate.id === providerThread.providerSessionId,
171 );
172 return providerSession?.capabilities.turns;
173}
174
175function resolveDeliveryIntent(
176 projection: OrchestrationV2ThreadProjection,
177 requestedMode: MessageDispatchMode,
178 deliveryIntent?: "auto" | "steer" | "restart",
179): MessageDispatchMode {
180 if (deliveryIntent === undefined) return requestedMode;
181
182 const activeRun = projection.runs.findLast(isActiveRun);
183 if (activeRun === undefined) return { type: "start_immediately" };
184 if (deliveryIntent === "steer") {
185 return { type: "steer_active", targetRunId: activeRun.id };
186 }
187 if (deliveryIntent === "restart") {
188 return { type: "restart_active", targetRunId: activeRun.id };
189 }
190 // A run can be active before its provider turn starts or after it finishes.
191 // Queue automatic input in those gaps so steering cannot reject the message.
192 if (
193 activeRun.status === "preparing" ||
194 activeRun.status === "starting" ||
195 !projection.providerTurns.some(
196 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
197 )
198 ) {
199 return { type: "queue_after_active" };
200 }
201
202 const capabilities = providerTurnCapabilities(projection, activeRun);
203 if (capabilities?.supportsActiveSteering === true) {
204 return { type: "steer_active", targetRunId: activeRun.id };
205 }
206 if (capabilities?.supportsQueuedMessages === true) {
207 return { type: "queue_after_active" };
208 }
209 if (capabilities?.supportsSteeringByInterruptRestart === true) {
210 return { type: "restart_active", targetRunId: activeRun.id };
211 }
212 return { type: "queue_after_active" };
213}
214
215interface CapabilityCheckInput {
216 readonly commandId: CommandId;
217 readonly threadId: ThreadId;
218 readonly providerInstanceId: ProviderInstanceId;
219 readonly capabilities: OrchestrationV2ProviderCapabilities;
220}
221
222export interface CommandPolicyV2Shape {
223 readonly ensureQueuedMessages: (
224 input: CapabilityCheckInput,
225 ) => Effect.Effect<void, CommandPolicyV2Error>;
226 readonly decideSteeringExecution: (
227 input: CapabilityCheckInput & {
228 readonly forceRestart?: boolean;
229 },
230 ) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>;
231 readonly ensureInterrupt: (
232 input: CapabilityCheckInput,
233 ) => Effect.Effect<void, CommandPolicyV2Error>;
234 readonly ensureNativeFork: (
235 input: CapabilityCheckInput & {
236 readonly fromSpecificTurn: boolean;
237 },
238 ) => Effect.Effect<void, CommandPolicyV2Error>;
239 readonly decideForkExecution: (
240 input: CapabilityCheckInput & {
241 readonly sameProvider: boolean;
242 readonly hasStrongNativeSource: boolean;
243 readonly hasNativeTurnBoundary: boolean;
244 readonly sourceRunStatus: OrchestrationV2Run["status"];
245 readonly fromSpecificTurn: boolean;
246 /** Later source runs are still active. */
247 readonly sourceBusy: boolean;
248 },
249 ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
250 readonly ensureRollback: (
251 input: CapabilityCheckInput,
252 ) => Effect.Effect<void, CommandPolicyV2Error>;
253 readonly ensureContextHandoff: (
254 input: CapabilityCheckInput & {
255 readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary";
256 },
257 ) => Effect.Effect<void, CommandPolicyV2Error>;
258}
259
260export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
261 "t3/orchestration-v2/CommandPolicy/CommandPolicyV2",
262) {}
263
264function unsupported(
265 input: CapabilityCheckInput,
266 capability: CommandPolicyCapability,
267 detail: string,
268) {
269 return new CommandPolicyCapabilityUnsupportedError({
270 commandId: input.commandId,
271 threadId: input.threadId,
272 providerInstanceId: input.providerInstanceId,
273 capability,
274 detail,
275 });
276}
277
278const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) =>
279 input.capabilities.turns.supportsQueuedMessages
280 ? Effect.void
281 : Effect.fail(
282 unsupported(
283 input,
284 "queued_messages",
285 "providerInstanceId does not support app-owned queued turns",
286 ),
287 );
288
289const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
290 if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {
291 return Effect.succeed("active_steering");
292 }
293 if (
294 input.capabilities.turns.supportsInterrupt &&
295 input.capabilities.turns.supportsSteeringByInterruptRestart
296 ) {
297 return Effect.succeed("interrupt_restart");
298 }
299 return Effect.fail(
300 unsupported(
301 input,
302 input.forceRestart || input.capabilities.turns.supportsInterrupt
303 ? "interrupt_restart_steering"
304 : "active_steering",
305 input.forceRestart
306 ? "providerInstanceId cannot satisfy a required interrupt-and-restart"
307 : "providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
308 ),
309 );
310};
311
312const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
313 input.capabilities.turns.supportsInterrupt
314 ? Effect.void
315 : Effect.fail(
316 unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
317 );
318
319const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
320 if (!input.capabilities.threads.canForkThread) {
321 return Effect.fail(
322 unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
323 );
324 }
325 if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
326 return Effect.fail(
327 unsupported(
328 input,
329 "fork_from_turn",
330 "providerInstanceId cannot fork from a specific completed turn",
331 ),
332 );
333 }
334 if (input.capabilities.identity.nativeThreadIds !== "strong") {
335 return Effect.fail(
336 unsupported(
337 input,
338 "native_fork",
339 "providerInstanceId does not expose strong native thread ids",
340 ),
341 );
342 }
343 return Effect.void;
344};
345
346const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
347 // Without native truncation, the next turn replays the kept conversation as a handoff.
348 if (
349 !input.capabilities.threads.canRollbackThread ||
350 (!input.capabilities.checkpointing.providerCanRollbackConversation &&
351 !input.capabilities.context.canConsumeHandoffSummaries)
352 ) {
353 return Effect.fail(
354 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
355 );
356 }
357 if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
358 return Effect.fail(
359 unsupported(
360 input,
361 "rollback_snapshot",
362 "rollback must return a providerInstanceId thread snapshot",
363 ),
364 );
365 }
366 return Effect.void;
367};
368
369const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
370 if (!input.capabilities.context.canConsumeHandoffSummaries) {
371 return Effect.fail(
372 unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
373 );
374 }
375 if (!input.capabilities.context.acceptsSyntheticUserContext) {
376 return Effect.fail(
377 unsupported(
378 input,
379 "context_handoff",
380 "providerInstanceId cannot receive synthetic user context",
381 ),
382 );
383 }
384 if (
385 (input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
386 !input.capabilities.context.supportsDeltaHandoff
387 ) {
388 return Effect.fail(
389 unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
390 );
391 }
392 if (
393 input.strategy === "full_thread_summary" &&
394 !input.capabilities.context.supportsFullThreadHandoff
395 ) {
396 return Effect.fail(
397 unsupported(
398 input,
399 "context_handoff",
400 "providerInstanceId does not support full-thread handoff",
401 ),
402 );
403 }
404 return Effect.void;
405};
406
407const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => {
408 // Unsuccessful runs may lack native cursors; fork bounded transcripts to exclude later turns.
409 const canForkNatively =
410 (input.sourceRunStatus === "completed" || input.sourceRunStatus === "waiting") &&
411 input.sameProvider &&
412 input.hasStrongNativeSource &&
413 (!input.sourceBusy ||
414 canForkBusySourceNatively(input.capabilities, input.hasNativeTurnBoundary)) &&
415 input.capabilities.threads.canForkThread &&
416 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
417 input.capabilities.identity.nativeThreadIds === "strong";
418
419 if (canForkNatively) {
420 return Effect.succeed("native_fork");
421 }
422
423 return ensureContextHandoff({
424 commandId: input.commandId,
425 threadId: input.threadId,
426 providerInstanceId: input.providerInstanceId,
427 capabilities: input.capabilities,
428 strategy: "full_thread_summary",
429 }).pipe(Effect.as("portable_context"));
430};
431
432export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
433 ensureQueuedMessages,
434 decideSteeringExecution,
435 ensureInterrupt,
436 ensureNativeFork,
437 decideForkExecution,
438 ensureRollback,
439 ensureContextHandoff,
440});