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

CommandPolicy.ts

486 lines16.0 KB

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 }
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 }
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 }
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 if (activeRun.status === "preparing" || activeRun.status === "starting") {
141 return { type: "queue_after_active" };
142 }
143​
144 const providerThread = projection.providerThreads.find(
145 (candidate) => candidate.id === activeRun.providerThreadId,
146 );
147 const providerSession =
148 providerThread?.providerSessionId == null
149 ? undefined
150 : projection.providerSessions.find(
151 (candidate) => candidate.id === providerThread.providerSessionId,
152 );
153 const capabilities = providerSession?.capabilities.turns;
154 if (capabilities?.supportsActiveSteering === true) {
155 return { type: "steer_active", targetRunId: activeRun.id };
156 }
157 if (capabilities?.supportsQueuedMessages === true) {
158 return { type: "queue_after_active" };
159 }
160 if (capabilities?.supportsSteeringByInterruptRestart === true) {
161 return { type: "restart_active", targetRunId: activeRun.id };
162 }
163 return { type: "queue_after_active" };
165​
166interface CapabilityCheckInput {
167 readonly commandId: CommandId;
168 readonly threadId: ThreadId;
169 readonly providerInstanceId: ProviderInstanceId;
170 readonly capabilities: OrchestrationV2ProviderCapabilities;
172​
173export interface CommandPolicyV2Shape {
174 readonly decideMessageDispatch: (input: {
175 readonly commandId: CommandId;
176 readonly projection: OrchestrationV2ThreadProjection;
177 readonly requestedModelSelection?: ModelSelection;
178 readonly requestedMode:
179 | { readonly type: "steer_active"; readonly targetRunId: RunId }
180 | { readonly type: "restart_active"; readonly targetRunId: RunId }
181 | { readonly type: "queue_after_active" }
182 | { readonly type: "start_immediately" };
183 readonly capabilities: OrchestrationV2ProviderCapabilities;
184 }) => Effect.Effect<MessageDispatchDecisionV2, CommandPolicyV2Error>;
185 readonly ensureQueuedMessages: (
186 input: CapabilityCheckInput,
187 ) => Effect.Effect<void, CommandPolicyV2Error>;
188 readonly decideSteeringExecution: (
189 input: CapabilityCheckInput & {
190 readonly forceRestart?: boolean;
191 },
192 ) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>;
193 readonly ensureInterrupt: (
194 input: CapabilityCheckInput,
195 ) => Effect.Effect<void, CommandPolicyV2Error>;
196 readonly ensureNativeFork: (
197 input: CapabilityCheckInput & {
198 readonly fromSpecificTurn: boolean;
199 },
200 ) => Effect.Effect<void, CommandPolicyV2Error>;
201 readonly decideForkExecution: (
202 input: CapabilityCheckInput & {
203 readonly sameProvider: boolean;
204 readonly hasStrongNativeSource: boolean;
205 readonly fromSpecificTurn: boolean;
206 },
207 ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
208 readonly ensureRollback: (
209 input: CapabilityCheckInput,
210 ) => Effect.Effect<void, CommandPolicyV2Error>;
211 readonly ensureContextHandoff: (
212 input: CapabilityCheckInput & {
213 readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary";
214 },
215 ) => Effect.Effect<void, CommandPolicyV2Error>;
217​
218export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
219 "t3/orchestration-v2/CommandPolicy/CommandPolicyV2",
220) {}
221​
222function unsupported(
223 input: CapabilityCheckInput,
224 capability: CommandPolicyCapability,
225 detail: string,
226) {
227 return new CommandPolicyCapabilityUnsupportedError({
228 commandId: input.commandId,
229 threadId: input.threadId,
230 providerInstanceId: input.providerInstanceId,
231 capability,
232 detail,
233 });
235​
236const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) =>
237 input.capabilities.turns.supportsQueuedMessages
238 ? Effect.void
239 : Effect.fail(
240 unsupported(
241 input,
242 "queued_messages",
243 "providerInstanceId does not support app-owned queued turns",
244 ),
245 );
246​
247const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
248 if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {
249 return Effect.succeed("active_steering");
250 }
251 if (
252 input.capabilities.turns.supportsInterrupt &&
253 input.capabilities.turns.supportsSteeringByInterruptRestart
254 ) {
255 return Effect.succeed("interrupt_restart");
256 }
257 return Effect.fail(
258 unsupported(
259 input,
260 input.forceRestart || input.capabilities.turns.supportsInterrupt
261 ? "interrupt_restart_steering"
262 : "active_steering",
263 input.forceRestart
264 ? "providerInstanceId cannot satisfy a required interrupt-and-restart"
265 : "providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
266 ),
267 );
268};
269​
270const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
271 input.capabilities.turns.supportsInterrupt
272 ? Effect.void
273 : Effect.fail(
274 unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
275 );
276​
277const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
278 if (!input.capabilities.threads.canForkThread) {
279 return Effect.fail(
280 unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
281 );
282 }
283 if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
284 return Effect.fail(
285 unsupported(
286 input,
287 "fork_from_turn",
288 "providerInstanceId cannot fork from a specific completed turn",
289 ),
290 );
291 }
292 if (input.capabilities.identity.nativeThreadIds !== "strong") {
293 return Effect.fail(
294 unsupported(
295 input,
296 "native_fork",
297 "providerInstanceId does not expose strong native thread ids",
298 ),
299 );
300 }
301 return Effect.void;
302};
303​
304const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
305 if (
306 !input.capabilities.threads.canRollbackThread ||
307 !input.capabilities.checkpointing.providerCanRollbackConversation
308 ) {
309 return Effect.fail(
310 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
311 );
312 }
313 if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
314 return Effect.fail(
315 unsupported(
316 input,
317 "rollback_snapshot",
318 "rollback must return a providerInstanceId thread snapshot",
319 ),
320 );
321 }
322 return Effect.void;
323};
324​
325const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
326 if (!input.capabilities.context.canConsumeHandoffSummaries) {
327 return Effect.fail(
328 unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
329 );
330 }
331 if (!input.capabilities.context.acceptsSyntheticUserContext) {
332 return Effect.fail(
333 unsupported(
334 input,
335 "context_handoff",
336 "providerInstanceId cannot receive synthetic user context",
337 ),
338 );
339 }
340 if (
341 (input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
342 !input.capabilities.context.supportsDeltaHandoff
343 ) {
344 return Effect.fail(
345 unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
346 );
347 }
348 if (
349 input.strategy === "full_thread_summary" &&
350 !input.capabilities.context.supportsFullThreadHandoff
351 ) {
352 return Effect.fail(
353 unsupported(
354 input,
355 "context_handoff",
356 "providerInstanceId does not support full-thread handoff",
357 ),
358 );
359 }
360 return Effect.void;
361};
362​
363const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => {
364 const canForkNatively =
365 input.sameProvider &&
366 input.hasStrongNativeSource &&
367 input.capabilities.threads.canForkThread &&
368 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
369 input.capabilities.identity.nativeThreadIds === "strong";
370​
371 if (canForkNatively) {
372 return Effect.succeed("native_fork");
373 }
374​
375 return ensureContextHandoff({
376 commandId: input.commandId,
377 threadId: input.threadId,
378 providerInstanceId: input.providerInstanceId,
379 capabilities: input.capabilities,
380 strategy: "full_thread_summary",
381 }).pipe(Effect.as("portable_context"));
382};
383​
384const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (input) => {
385 const activeRun = input.projection.runs.find(
386 (run) =>
387 run.status === "preparing" ||
388 run.status === "starting" ||
389 run.status === "running" ||
390 run.status === "waiting",
391 );
392 const modelSelection = input.requestedModelSelection ?? input.projection.thread.modelSelection;
393​
394 switch (input.requestedMode.type) {
395 case "steer_active": {
396 if (activeRun?.id !== input.requestedMode.targetRunId) {
397 return Effect.fail(
398 new CommandPolicyUnsupportedError({
399 commandId: input.commandId,
400 threadId: input.projection.thread.id,
401 requestedMode: input.requestedMode.type,
402 providerInstanceId: modelSelection.instanceId,
403 }),
404 );
405 }
406 const providerTurnId =
407 activeRun.activeAttemptId === null
408 ? undefined
409 : input.projection.providerTurns.find(
410 (turn) =>
411 turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
412 )?.id;
413 return providerTurnId === undefined
414 ? Effect.fail(
415 new CommandPolicyMessageDispatchError({
416 commandId: input.commandId,
417 threadId: input.projection.thread.id,
418 cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
419 }),
420 )
421 : Effect.succeed({
422 type: "steer_active",
423 targetRunId: activeRun.id,
424 providerTurnId,
425 });
426 }
427 case "restart_active": {
428 if (activeRun?.id !== input.requestedMode.targetRunId || activeRun.activeAttemptId === null) {
429 return Effect.fail(
430 new CommandPolicyUnsupportedError({
431 commandId: input.commandId,
432 threadId: input.projection.thread.id,
433 requestedMode: input.requestedMode.type,
434 providerInstanceId: modelSelection.instanceId,
435 }),
436 );
437 }
438 const providerTurnId = input.projection.providerTurns.find(
439 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
440 )?.id;
441 return providerTurnId === undefined
442 ? Effect.fail(
443 new CommandPolicyMessageDispatchError({
444 commandId: input.commandId,
445 threadId: input.projection.thread.id,
446 cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
447 }),
448 )
449 : Effect.succeed({
450 type: "restart_active",
451 targetRunId: activeRun.id,
452 interruptProviderTurnId: providerTurnId,
453 });
454 }
455 case "queue_after_active":
456 return activeRun === undefined
457 ? Effect.succeed({ type: "start_run", modelSelection })
458 : ensureQueuedMessages({
459 commandId: input.commandId,
460 threadId: input.projection.thread.id,
461 providerInstanceId: modelSelection.instanceId,
462 capabilities: input.capabilities,
463 }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
464 case "start_immediately":
465 if (activeRun === undefined) {
466 return Effect.succeed({ type: "start_run", modelSelection });
467 }
468 return ensureQueuedMessages({
469 commandId: input.commandId,
470 threadId: input.projection.thread.id,
471 providerInstanceId: modelSelection.instanceId,
472 capabilities: input.capabilities,
473 }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
474 }
475};
476​
477export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
478 decideMessageDispatch,
479 ensureQueuedMessages,
480 decideSteeringExecution,
481 ensureInterrupt,
482 ensureNativeFork,
483 decideForkExecution,
484 ensureRollback,
485 ensureContextHandoff,
486});