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

CommandPolicy.ts

428 lines14.0 KB

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