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

CommandPolicy.ts

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