Open History to see the last commit
1import {
2 CommandId,
3 ModelSelection,
4 type OrchestrationV2Command,
5 OrchestrationV2ProviderCapabilities,
6 OrchestrationV2ThreadProjection,
7 ProviderInstanceId,
8 ProviderTurnId,
9 RunId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Schema from "effect/Schema";
16
17export const MessageDispatchDecisionV2 = Schema.Union([
18 Schema.Struct({
19 type: Schema.Literal("start_run"),
20 modelSelection: ModelSelection,
21 }),
22 Schema.Struct({
23 type: Schema.Literal("steer_active"),
24 targetRunId: RunId,
25 providerTurnId: ProviderTurnId,
26 }),
27 Schema.Struct({
28 type: Schema.Literal("restart_active"),
29 targetRunId: RunId,
30 interruptProviderTurnId: ProviderTurnId,
31 }),
32 Schema.Struct({
33 type: Schema.Literal("queue_after_active"),
34 activeRunId: RunId,
35 }),
36 Schema.Struct({
37 type: Schema.Literal("switch_provider"),
38 fromProviderInstanceId: ProviderInstanceId,
39 toModelSelection: ModelSelection,
40 }),
41]);
42export type MessageDispatchDecisionV2 = typeof MessageDispatchDecisionV2.Type;
43
44export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]);
45export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type;
46
47export const ForkExecutionPolicyV2 = Schema.Literals(["native_fork", "portable_context"]);
48export type ForkExecutionPolicyV2 = typeof ForkExecutionPolicyV2.Type;
49
50export const CommandPolicyCapability = Schema.Literals([
51 "queued_messages",
52 "active_steering",
53 "interrupt",
54 "interrupt_restart_steering",
55 "native_fork",
56 "fork_from_turn",
57 "rollback",
58 "rollback_snapshot",
59 "context_handoff",
60 "strong_terminal_status",
61]);
62export type CommandPolicyCapability = typeof CommandPolicyCapability.Type;
63
64export class CommandPolicyMessageDispatchError extends Schema.TaggedError<CommandPolicyMessageDispatchError>()(
65 "CommandPolicyMessageDispatchError",
66 {
67 commandId: CommandId,
68 threadId: ThreadId,
69 cause: Schema.optional(Schema.Defect()),
70 },
71) {
72 override get message(): string {
73 return `Failed to choose message dispatch policy for command ${this.commandId}.`;
74 }
75}
76
77export class CommandPolicyUnsupportedError extends Schema.TaggedError<CommandPolicyUnsupportedError>()(
78 "CommandPolicyUnsupportedError",
79 {
80 commandId: CommandId,
81 threadId: ThreadId,
82 requestedMode: Schema.String,
83 providerInstanceId: ProviderInstanceId,
84 },
85) {
86 override get message(): string {
87 return `${this.providerInstanceId} cannot satisfy message dispatch mode ${this.requestedMode} for command ${this.commandId}.`;
88 }
89}
90
91export class CommandPolicyCapabilityUnsupportedError extends Schema.TaggedError<CommandPolicyCapabilityUnsupportedError>()(
92 "CommandPolicyCapabilityUnsupportedError",
93 {
94 commandId: CommandId,
95 threadId: ThreadId,
96 providerInstanceId: ProviderInstanceId,
97 capability: CommandPolicyCapability,
98 detail: Schema.String,
99 },
100) {
101 override get message(): string {
102 return `${this.providerInstanceId} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`;
103 }
104}
105
106export const CommandPolicyV2Error = Schema.Union([
107 CommandPolicyMessageDispatchError,
108 CommandPolicyUnsupportedError,
109 CommandPolicyCapabilityUnsupportedError,
110]);
111export type CommandPolicyV2Error = typeof CommandPolicyV2Error.Type;
112
113type MessageDispatchMode = Extract<
114 OrchestrationV2Command,
115 { readonly type: "message.dispatch" }
116>["dispatchMode"];
117
118/** Resolve client intent from the state serialized by the thread dispatch lock. */
119export function resolveMessageDispatchIntent(
120 projection: OrchestrationV2ThreadProjection,
121 requestedMode: MessageDispatchMode,
122 deliveryIntent?: "auto" | "steer" | "restart",
123): MessageDispatchMode {
124 if (deliveryIntent === undefined) return requestedMode;
125
126 const activeRun = projection.runs.findLast(
127 (run) =>
128 run.status === "preparing" ||
129 run.status === "starting" ||
130 run.status === "running" ||
131 run.status === "waiting",
132 );
133 if (activeRun === undefined) return { type: "start_immediately" };
134 if (deliveryIntent === "steer") {
135 return { type: "steer_active", targetRunId: activeRun.id };
136 }
137 if (deliveryIntent === "restart") {
138 return { type: "restart_active", targetRunId: activeRun.id };
139 }
140
141 const providerThread = projection.providerThreads.find(
142 (candidate) => candidate.id === activeRun.providerThreadId,
143 );
144 const providerSession =
145 providerThread?.providerSessionId == null
146 ? undefined
147 : projection.providerSessions.find(
148 (candidate) => candidate.id === providerThread.providerSessionId,
149 );
150 const capabilities = providerSession?.capabilities.turns;
151 if (capabilities?.supportsActiveSteering === true) {
152 return { type: "steer_active", targetRunId: activeRun.id };
153 }
154 if (capabilities?.supportsQueuedMessages === true) {
155 return { type: "queue_after_active" };
156 }
157 if (capabilities?.supportsSteeringByInterruptRestart === true) {
158 return { type: "restart_active", targetRunId: activeRun.id };
159 }
160 return { type: "queue_after_active" };
161}
162
163interface CapabilityCheckInput {
164 readonly commandId: CommandId;
165 readonly threadId: ThreadId;
166 readonly providerInstanceId: ProviderInstanceId;
167 readonly capabilities: OrchestrationV2ProviderCapabilities;
168}
169
170export interface CommandPolicyV2Shape {
171 readonly decideMessageDispatch: (input: {
172 readonly commandId: CommandId;
173 readonly projection: OrchestrationV2ThreadProjection;
174 readonly requestedModelSelection?: ModelSelection;
175 readonly requestedMode:
176 | { readonly type: "steer_active"; readonly targetRunId: RunId }
177 | { readonly type: "restart_active"; readonly targetRunId: RunId }
178 | { readonly type: "queue_after_active" }
179 | { readonly type: "start_immediately" };
180 readonly capabilities: OrchestrationV2ProviderCapabilities;
181 }) => Effect.Effect<MessageDispatchDecisionV2, CommandPolicyV2Error>;
182 readonly ensureQueuedMessages: (
183 input: CapabilityCheckInput,
184 ) => Effect.Effect<void, CommandPolicyV2Error>;
185 readonly decideSteeringExecution: (
186 input: CapabilityCheckInput & {
187 readonly forceRestart?: boolean;
188 },
189 ) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>;
190 readonly ensureInterrupt: (
191 input: CapabilityCheckInput,
192 ) => Effect.Effect<void, CommandPolicyV2Error>;
193 readonly ensureNativeFork: (
194 input: CapabilityCheckInput & {
195 readonly fromSpecificTurn: boolean;
196 },
197 ) => Effect.Effect<void, CommandPolicyV2Error>;
198 readonly decideForkExecution: (
199 input: CapabilityCheckInput & {
200 readonly sameProvider: boolean;
201 readonly hasStrongNativeSource: boolean;
202 readonly fromSpecificTurn: boolean;
203 },
204 ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
205 readonly ensureRollback: (
206 input: CapabilityCheckInput,
207 ) => Effect.Effect<void, CommandPolicyV2Error>;
208 readonly ensureContextHandoff: (
209 input: CapabilityCheckInput & {
210 readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary";
211 },
212 ) => Effect.Effect<void, CommandPolicyV2Error>;
213}
214
215export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
216 "t3/orchestration-v2/CommandPolicy/CommandPolicyV2",
217) {}
218
219function unsupported(
220 input: CapabilityCheckInput,
221 capability: CommandPolicyCapability,
222 detail: string,
223) {
224 return new CommandPolicyCapabilityUnsupportedError({
225 commandId: input.commandId,
226 threadId: input.threadId,
227 providerInstanceId: input.providerInstanceId,
228 capability,
229 detail,
230 });
231}
232
233const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) =>
234 input.capabilities.turns.supportsQueuedMessages
235 ? Effect.void
236 : Effect.fail(
237 unsupported(
238 input,
239 "queued_messages",
240 "providerInstanceId does not support app-owned queued turns",
241 ),
242 );
243
244const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
245 if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {
246 return Effect.succeed("active_steering");
247 }
248 if (
249 input.capabilities.turns.supportsInterrupt &&
250 input.capabilities.turns.supportsSteeringByInterruptRestart
251 ) {
252 return Effect.succeed("interrupt_restart");
253 }
254 return Effect.fail(
255 unsupported(
256 input,
257 input.capabilities.turns.supportsInterrupt ? "interrupt_restart_steering" : "active_steering",
258 "providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
259 ),
260 );
261};
262
263const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
264 input.capabilities.turns.supportsInterrupt
265 ? Effect.void
266 : Effect.fail(
267 unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
268 );
269
270const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
271 if (!input.capabilities.threads.canForkThread) {
272 return Effect.fail(
273 unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
274 );
275 }
276 if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
277 return Effect.fail(
278 unsupported(
279 input,
280 "fork_from_turn",
281 "providerInstanceId cannot fork from a specific completed turn",
282 ),
283 );
284 }
285 if (input.capabilities.identity.nativeThreadIds !== "strong") {
286 return Effect.fail(
287 unsupported(
288 input,
289 "native_fork",
290 "providerInstanceId does not expose strong native thread ids",
291 ),
292 );
293 }
294 return Effect.void;
295};
296
297const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
298 if (
299 !input.capabilities.threads.canRollbackThread ||
300 !input.capabilities.checkpointing.providerCanRollbackConversation
301 ) {
302 return Effect.fail(
303 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
304 );
305 }
306 if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
307 return Effect.fail(
308 unsupported(
309 input,
310 "rollback_snapshot",
311 "rollback must return a providerInstanceId thread snapshot",
312 ),
313 );
314 }
315 return Effect.void;
316};
317
318const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
319 if (!input.capabilities.context.canConsumeHandoffSummaries) {
320 return Effect.fail(
321 unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
322 );
323 }
324 if (!input.capabilities.context.acceptsSyntheticUserContext) {
325 return Effect.fail(
326 unsupported(
327 input,
328 "context_handoff",
329 "providerInstanceId cannot receive synthetic user context",
330 ),
331 );
332 }
333 if (
334 (input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
335 !input.capabilities.context.supportsDeltaHandoff
336 ) {
337 return Effect.fail(
338 unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
339 );
340 }
341 if (
342 input.strategy === "full_thread_summary" &&
343 !input.capabilities.context.supportsFullThreadHandoff
344 ) {
345 return Effect.fail(
346 unsupported(
347 input,
348 "context_handoff",
349 "providerInstanceId does not support full-thread handoff",
350 ),
351 );
352 }
353 return Effect.void;
354};
355
356const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => {
357 const canForkNatively =
358 input.sameProvider &&
359 input.hasStrongNativeSource &&
360 input.capabilities.threads.canForkThread &&
361 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
362 input.capabilities.identity.nativeThreadIds === "strong";
363
364 if (canForkNatively) {
365 return Effect.succeed("native_fork");
366 }
367
368 return ensureContextHandoff({
369 commandId: input.commandId,
370 threadId: input.threadId,
371 providerInstanceId: input.providerInstanceId,
372 capabilities: input.capabilities,
373 strategy: "full_thread_summary",
374 }).pipe(Effect.as("portable_context"));
375};
376
377const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (input) => {
378 const activeRun = input.projection.runs.find(
379 (run) =>
380 run.status === "preparing" ||
381 run.status === "starting" ||
382 run.status === "running" ||
383 run.status === "waiting",
384 );
385 const modelSelection = input.requestedModelSelection ?? input.projection.thread.modelSelection;
386
387 switch (input.requestedMode.type) {
388 case "steer_active": {
389 if (activeRun?.id !== input.requestedMode.targetRunId) {
390 return Effect.fail(
391 new CommandPolicyUnsupportedError({
392 commandId: input.commandId,
393 threadId: input.projection.thread.id,
394 requestedMode: input.requestedMode.type,
395 providerInstanceId: modelSelection.instanceId,
396 }),
397 );
398 }
399 const providerTurnId =
400 activeRun.activeAttemptId === null
401 ? undefined
402 : input.projection.providerTurns.find(
403 (turn) =>
404 turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
405 )?.id;
406 return providerTurnId === undefined
407 ? Effect.fail(
408 new CommandPolicyMessageDispatchError({
409 commandId: input.commandId,
410 threadId: input.projection.thread.id,
411 cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
412 }),
413 )
414 : Effect.succeed({
415 type: "steer_active",
416 targetRunId: activeRun.id,
417 providerTurnId,
418 });
419 }
420 case "restart_active": {
421 if (activeRun?.id !== input.requestedMode.targetRunId || activeRun.activeAttemptId === null) {
422 return Effect.fail(
423 new CommandPolicyUnsupportedError({
424 commandId: input.commandId,
425 threadId: input.projection.thread.id,
426 requestedMode: input.requestedMode.type,
427 providerInstanceId: modelSelection.instanceId,
428 }),
429 );
430 }
431 const providerTurnId = input.projection.providerTurns.find(
432 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
433 )?.id;
434 return providerTurnId === undefined
435 ? Effect.fail(
436 new CommandPolicyMessageDispatchError({
437 commandId: input.commandId,
438 threadId: input.projection.thread.id,
439 cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
440 }),
441 )
442 : Effect.succeed({
443 type: "restart_active",
444 targetRunId: activeRun.id,
445 interruptProviderTurnId: providerTurnId,
446 });
447 }
448 case "queue_after_active":
449 return activeRun === undefined
450 ? Effect.succeed({ type: "start_run", modelSelection })
451 : ensureQueuedMessages({
452 commandId: input.commandId,
453 threadId: input.projection.thread.id,
454 providerInstanceId: modelSelection.instanceId,
455 capabilities: input.capabilities,
456 }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
457 case "start_immediately":
458 if (activeRun === undefined) {
459 return Effect.succeed({ type: "start_run", modelSelection });
460 }
461 return ensureQueuedMessages({
462 commandId: input.commandId,
463 threadId: input.projection.thread.id,
464 providerInstanceId: modelSelection.instanceId,
465 capabilities: input.capabilities,
466 }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
467 }
468};
469
470export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
471 decideMessageDispatch,
472 ensureQueuedMessages,
473 decideSteeringExecution,
474 ensureInterrupt,
475 ensureNativeFork,
476 decideForkExecution,
477 ensureRollback,
478 ensureContextHandoff,
479});