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

CommandPolicy.ts

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