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

CommandPolicy.ts

518 lines17.4 KB

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