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

CommandPolicy.ts

483 lines15.9 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​
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" };
162​
163interface CapabilityCheckInput {
164 readonly commandId: CommandId;
165 readonly threadId: ThreadId;
166 readonly providerInstanceId: ProviderInstanceId;
167 readonly capabilities: OrchestrationV2ProviderCapabilities;
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>;
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 });
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.forceRestart || input.capabilities.turns.supportsInterrupt
258 ? "interrupt_restart_steering"
259 : "active_steering",
260 input.forceRestart
261 ? "providerInstanceId cannot satisfy a required interrupt-and-restart"
262 : "providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
263 ),
264 );
265};
266​
267const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
268 input.capabilities.turns.supportsInterrupt
269 ? Effect.void
270 : Effect.fail(
271 unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
272 );
273​
274const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
275 if (!input.capabilities.threads.canForkThread) {
276 return Effect.fail(
277 unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
278 );
279 }
280 if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
281 return Effect.fail(
282 unsupported(
283 input,
284 "fork_from_turn",
285 "providerInstanceId cannot fork from a specific completed turn",
286 ),
287 );
288 }
289 if (input.capabilities.identity.nativeThreadIds !== "strong") {
290 return Effect.fail(
291 unsupported(
292 input,
293 "native_fork",
294 "providerInstanceId does not expose strong native thread ids",
295 ),
296 );
297 }
298 return Effect.void;
299};
300​
301const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
302 if (
303 !input.capabilities.threads.canRollbackThread ||
304 !input.capabilities.checkpointing.providerCanRollbackConversation
305 ) {
306 return Effect.fail(
307 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
308 );
309 }
310 if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
311 return Effect.fail(
312 unsupported(
313 input,
314 "rollback_snapshot",
315 "rollback must return a providerInstanceId thread snapshot",
316 ),
317 );
318 }
319 return Effect.void;
320};
321​
322const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
323 if (!input.capabilities.context.canConsumeHandoffSummaries) {
324 return Effect.fail(
325 unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
326 );
327 }
328 if (!input.capabilities.context.acceptsSyntheticUserContext) {
329 return Effect.fail(
330 unsupported(
331 input,
332 "context_handoff",
333 "providerInstanceId cannot receive synthetic user context",
334 ),
335 );
336 }
337 if (
338 (input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
339 !input.capabilities.context.supportsDeltaHandoff
340 ) {
341 return Effect.fail(
342 unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
343 );
344 }
345 if (
346 input.strategy === "full_thread_summary" &&
347 !input.capabilities.context.supportsFullThreadHandoff
348 ) {
349 return Effect.fail(
350 unsupported(
351 input,
352 "context_handoff",
353 "providerInstanceId does not support full-thread handoff",
354 ),
355 );
356 }
357 return Effect.void;
358};
359​
360const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => {
361 const canForkNatively =
362 input.sameProvider &&
363 input.hasStrongNativeSource &&
364 input.capabilities.threads.canForkThread &&
365 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
366 input.capabilities.identity.nativeThreadIds === "strong";
367​
368 if (canForkNatively) {
369 return Effect.succeed("native_fork");
370 }
371​
372 return ensureContextHandoff({
373 commandId: input.commandId,
374 threadId: input.threadId,
375 providerInstanceId: input.providerInstanceId,
376 capabilities: input.capabilities,
377 strategy: "full_thread_summary",
378 }).pipe(Effect.as("portable_context"));
379};
380​
381const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (input) => {
382 const activeRun = input.projection.runs.find(
383 (run) =>
384 run.status === "preparing" ||
385 run.status === "starting" ||
386 run.status === "running" ||
387 run.status === "waiting",
388 );
389 const modelSelection = input.requestedModelSelection ?? input.projection.thread.modelSelection;
390​
391 switch (input.requestedMode.type) {
392 case "steer_active": {
393 if (activeRun?.id !== input.requestedMode.targetRunId) {
394 return Effect.fail(
395 new CommandPolicyUnsupportedError({
396 commandId: input.commandId,
397 threadId: input.projection.thread.id,
398 requestedMode: input.requestedMode.type,
399 providerInstanceId: modelSelection.instanceId,
400 }),
401 );
402 }
403 const providerTurnId =
404 activeRun.activeAttemptId === null
405 ? undefined
406 : input.projection.providerTurns.find(
407 (turn) =>
408 turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
409 )?.id;
410 return providerTurnId === undefined
411 ? Effect.fail(
412 new CommandPolicyMessageDispatchError({
413 commandId: input.commandId,
414 threadId: input.projection.thread.id,
415 cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
416 }),
417 )
418 : Effect.succeed({
419 type: "steer_active",
420 targetRunId: activeRun.id,
421 providerTurnId,
422 });
423 }
424 case "restart_active": {
425 if (activeRun?.id !== input.requestedMode.targetRunId || activeRun.activeAttemptId === null) {
426 return Effect.fail(
427 new CommandPolicyUnsupportedError({
428 commandId: input.commandId,
429 threadId: input.projection.thread.id,
430 requestedMode: input.requestedMode.type,
431 providerInstanceId: modelSelection.instanceId,
432 }),
433 );
434 }
435 const providerTurnId = input.projection.providerTurns.find(
436 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
437 )?.id;
438 return providerTurnId === undefined
439 ? Effect.fail(
440 new CommandPolicyMessageDispatchError({
441 commandId: input.commandId,
442 threadId: input.projection.thread.id,
443 cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
444 }),
445 )
446 : Effect.succeed({
447 type: "restart_active",
448 targetRunId: activeRun.id,
449 interruptProviderTurnId: providerTurnId,
450 });
451 }
452 case "queue_after_active":
453 return activeRun === undefined
454 ? Effect.succeed({ type: "start_run", modelSelection })
455 : ensureQueuedMessages({
456 commandId: input.commandId,
457 threadId: input.projection.thread.id,
458 providerInstanceId: modelSelection.instanceId,
459 capabilities: input.capabilities,
460 }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
461 case "start_immediately":
462 if (activeRun === undefined) {
463 return Effect.succeed({ type: "start_run", modelSelection });
464 }
465 return ensureQueuedMessages({
466 commandId: input.commandId,
467 threadId: input.projection.thread.id,
468 providerInstanceId: modelSelection.instanceId,
469 capabilities: input.capabilities,
470 }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
471 }
472};
473​
474export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
475 decideMessageDispatch,
476 ensureQueuedMessages,
477 decideSteeringExecution,
478 ensureInterrupt,
479 ensureNativeFork,
480 decideForkExecution,
481 ensureRollback,
482 ensureContextHandoff,
483});