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

CommandPolicy.ts

546 lines18.1 KB

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