Open History to see the last commit
1import {
2 type ChatAttachment,
3 CommandId,
4 type OrchestrationV2Command,
5 OrchestrationV2ProviderCapabilities,
6 type OrchestrationV2GoalCommand,
7 type OrchestrationV2ProviderGoalStatus,
8 type OrchestrationV2Run,
9 OrchestrationV2ThreadProjection,
10 ProviderInstanceId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17
18export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]);
19export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type;
20
21export const ForkExecutionPolicyV2 = Schema.Literals(["native_fork", "portable_context"]);
22export type ForkExecutionPolicyV2 = typeof ForkExecutionPolicyV2.Type;
23
24export const CommandPolicyCapability = Schema.Literals([
25 "queued_messages",
26 "active_steering",
27 "interrupt",
28 "interrupt_restart_steering",
29 "native_fork",
30 "fork_from_turn",
31 "rollback",
32 "rollback_snapshot",
33 "context_handoff",
34 "strong_terminal_status",
35]);
36export type CommandPolicyCapability = typeof CommandPolicyCapability.Type;
37
38export class CommandPolicyCapabilityUnsupportedError extends Schema.TaggedError<CommandPolicyCapabilityUnsupportedError>()(
39 "CommandPolicyCapabilityUnsupportedError",
40 {
41 commandId: CommandId,
42 threadId: ThreadId,
43 providerInstanceId: ProviderInstanceId,
44 capability: CommandPolicyCapability,
45 detail: Schema.String,
46 },
47) {
48 override get message(): string {
49 return `${this.providerInstanceId} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`;
50 }
51}
52
53export const CommandPolicyV2Error = Schema.Union([CommandPolicyCapabilityUnsupportedError]);
54export type CommandPolicyV2Error = typeof CommandPolicyV2Error.Type;
55
56type MessageDispatchMode = Extract<
57 OrchestrationV2Command,
58 { readonly type: "message.dispatch" }
59>["dispatchMode"];
60
61export function isNativeMaintenanceCommand(message: {
62 readonly text: string;
63 readonly attachments: ReadonlyArray<ChatAttachment>;
64 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
65}): boolean {
66 return (
67 message.attachments.length === 0 &&
68 ["/compact", "/logout"].includes(message.text.trim().toLowerCase())
69 );
70}
71
72/**
73 * A goal command sent into active work stops that work when it starts or
74 * replaces goal work, or ends a goal that is driving the run.
75 */
76export function goalCommandStopsActiveRun(
77 command: OrchestrationV2GoalCommand,
78 goalStatus: OrchestrationV2ProviderGoalStatus | null,
79): boolean {
80 switch (command.type) {
81 case "set":
82 case "resume":
83 return true;
84 case "clear":
85 case "pause":
86 return goalStatus === "active";
87 case "show":
88 return false;
89 }
90}
91
92export function resolveMessageDispatchIntent(
93 projection: OrchestrationV2ThreadProjection,
94 requestedMode: MessageDispatchMode,
95 deliveryIntent?: "auto" | "steer" | "restart",
96): MessageDispatchMode {
97 const mode = resolveDeliveryIntent(projection, requestedMode, deliveryIntent);
98 if (mode.type !== "steer_active") return mode;
99 // Compaction and sign-out cannot accept steers; queue follow-ups.
100 const target = projection.runs.find((run) => run.id === mode.targetRunId);
101 const targetMessage = projection.messages.find((message) => message.id === target?.userMessageId);
102 if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) {
103 return { type: "queue_after_active" };
104 }
105 // A provider that can neither steer nor restart its turn takes the message after the turn.
106 const turns =
107 target === undefined || !isActiveRun(target)
108 ? undefined
109 : providerTurnCapabilities(projection, target);
110 return turns !== undefined &&
111 !turns.supportsActiveSteering &&
112 !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) &&
113 turns.supportsQueuedMessages
114 ? { type: "queue_after_active" }
115 : mode;
116}
117
118function isActiveRun(run: OrchestrationV2Run): boolean {
119 return (
120 run.status === "preparing" ||
121 run.status === "starting" ||
122 run.status === "running" ||
123 run.status === "waiting"
124 );
125}
126
127function providerTurnCapabilities(
128 projection: OrchestrationV2ThreadProjection,
129 run: OrchestrationV2Run,
130) {
131 const providerThread = projection.providerThreads.find(
132 (candidate) => candidate.id === run.providerThreadId,
133 );
134 const providerSession =
135 providerThread?.providerSessionId == null
136 ? undefined
137 : projection.providerSessions.find(
138 (candidate) => candidate.id === providerThread.providerSessionId,
139 );
140 return providerSession?.capabilities.turns;
141}
142
143function resolveDeliveryIntent(
144 projection: OrchestrationV2ThreadProjection,
145 requestedMode: MessageDispatchMode,
146 deliveryIntent?: "auto" | "steer" | "restart",
147): MessageDispatchMode {
148 if (deliveryIntent === undefined) return requestedMode;
149
150 const activeRun = projection.runs.findLast(isActiveRun);
151 if (activeRun === undefined) return { type: "start_immediately" };
152 if (deliveryIntent === "steer") {
153 return { type: "steer_active", targetRunId: activeRun.id };
154 }
155 if (deliveryIntent === "restart") {
156 return { type: "restart_active", targetRunId: activeRun.id };
157 }
158 // A run can be active before its provider turn starts or after it finishes.
159 // Queue automatic input in those gaps so steering cannot reject the message.
160 if (
161 activeRun.status === "preparing" ||
162 activeRun.status === "starting" ||
163 !projection.providerTurns.some(
164 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
165 )
166 ) {
167 return { type: "queue_after_active" };
168 }
169
170 const capabilities = providerTurnCapabilities(projection, activeRun);
171 if (capabilities?.supportsActiveSteering === true) {
172 return { type: "steer_active", targetRunId: activeRun.id };
173 }
174 if (capabilities?.supportsQueuedMessages === true) {
175 return { type: "queue_after_active" };
176 }
177 if (capabilities?.supportsSteeringByInterruptRestart === true) {
178 return { type: "restart_active", targetRunId: activeRun.id };
179 }
180 return { type: "queue_after_active" };
181}
182
183interface CapabilityCheckInput {
184 readonly commandId: CommandId;
185 readonly threadId: ThreadId;
186 readonly providerInstanceId: ProviderInstanceId;
187 readonly capabilities: OrchestrationV2ProviderCapabilities;
188}
189
190export interface CommandPolicyV2Shape {
191 readonly ensureQueuedMessages: (
192 input: CapabilityCheckInput,
193 ) => Effect.Effect<void, CommandPolicyV2Error>;
194 readonly decideSteeringExecution: (
195 input: CapabilityCheckInput & {
196 readonly forceRestart?: boolean;
197 },
198 ) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>;
199 readonly ensureInterrupt: (
200 input: CapabilityCheckInput,
201 ) => Effect.Effect<void, CommandPolicyV2Error>;
202 readonly ensureNativeFork: (
203 input: CapabilityCheckInput & {
204 readonly fromSpecificTurn: boolean;
205 },
206 ) => Effect.Effect<void, CommandPolicyV2Error>;
207 readonly decideForkExecution: (
208 input: CapabilityCheckInput & {
209 readonly sameProvider: boolean;
210 readonly hasStrongNativeSource: boolean;
211 readonly sourceRunStatus: OrchestrationV2Run["status"];
212 readonly fromSpecificTurn: boolean;
213 },
214 ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
215 readonly ensureRollback: (
216 input: CapabilityCheckInput,
217 ) => Effect.Effect<void, CommandPolicyV2Error>;
218 readonly ensureContextHandoff: (
219 input: CapabilityCheckInput & {
220 readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary";
221 },
222 ) => Effect.Effect<void, CommandPolicyV2Error>;
223}
224
225export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
226 "t3/orchestration-v2/CommandPolicy/CommandPolicyV2",
227) {}
228
229function unsupported(
230 input: CapabilityCheckInput,
231 capability: CommandPolicyCapability,
232 detail: string,
233) {
234 return new CommandPolicyCapabilityUnsupportedError({
235 commandId: input.commandId,
236 threadId: input.threadId,
237 providerInstanceId: input.providerInstanceId,
238 capability,
239 detail,
240 });
241}
242
243const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) =>
244 input.capabilities.turns.supportsQueuedMessages
245 ? Effect.void
246 : Effect.fail(
247 unsupported(
248 input,
249 "queued_messages",
250 "providerInstanceId does not support app-owned queued turns",
251 ),
252 );
253
254const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
255 if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {
256 return Effect.succeed("active_steering");
257 }
258 if (
259 input.capabilities.turns.supportsInterrupt &&
260 input.capabilities.turns.supportsSteeringByInterruptRestart
261 ) {
262 return Effect.succeed("interrupt_restart");
263 }
264 return Effect.fail(
265 unsupported(
266 input,
267 input.forceRestart || input.capabilities.turns.supportsInterrupt
268 ? "interrupt_restart_steering"
269 : "active_steering",
270 input.forceRestart
271 ? "providerInstanceId cannot satisfy a required interrupt-and-restart"
272 : "providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
273 ),
274 );
275};
276
277const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
278 input.capabilities.turns.supportsInterrupt
279 ? Effect.void
280 : Effect.fail(
281 unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
282 );
283
284const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
285 if (!input.capabilities.threads.canForkThread) {
286 return Effect.fail(
287 unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
288 );
289 }
290 if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
291 return Effect.fail(
292 unsupported(
293 input,
294 "fork_from_turn",
295 "providerInstanceId cannot fork from a specific completed turn",
296 ),
297 );
298 }
299 if (input.capabilities.identity.nativeThreadIds !== "strong") {
300 return Effect.fail(
301 unsupported(
302 input,
303 "native_fork",
304 "providerInstanceId does not expose strong native thread ids",
305 ),
306 );
307 }
308 return Effect.void;
309};
310
311const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
312 if (
313 !input.capabilities.threads.canRollbackThread ||
314 !input.capabilities.checkpointing.providerCanRollbackConversation
315 ) {
316 return Effect.fail(
317 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
318 );
319 }
320 if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
321 return Effect.fail(
322 unsupported(
323 input,
324 "rollback_snapshot",
325 "rollback must return a providerInstanceId thread snapshot",
326 ),
327 );
328 }
329 return Effect.void;
330};
331
332const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
333 if (!input.capabilities.context.canConsumeHandoffSummaries) {
334 return Effect.fail(
335 unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
336 );
337 }
338 if (!input.capabilities.context.acceptsSyntheticUserContext) {
339 return Effect.fail(
340 unsupported(
341 input,
342 "context_handoff",
343 "providerInstanceId cannot receive synthetic user context",
344 ),
345 );
346 }
347 if (
348 (input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
349 !input.capabilities.context.supportsDeltaHandoff
350 ) {
351 return Effect.fail(
352 unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
353 );
354 }
355 if (
356 input.strategy === "full_thread_summary" &&
357 !input.capabilities.context.supportsFullThreadHandoff
358 ) {
359 return Effect.fail(
360 unsupported(
361 input,
362 "context_handoff",
363 "providerInstanceId does not support full-thread handoff",
364 ),
365 );
366 }
367 return Effect.void;
368};
369
370const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => {
371 // Unsuccessful runs may lack native cursors; fork bounded transcripts to exclude later turns.
372 const canForkNatively =
373 (input.sourceRunStatus === "completed" || input.sourceRunStatus === "waiting") &&
374 input.sameProvider &&
375 input.hasStrongNativeSource &&
376 input.capabilities.threads.canForkThread &&
377 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
378 input.capabilities.identity.nativeThreadIds === "strong";
379
380 if (canForkNatively) {
381 return Effect.succeed("native_fork");
382 }
383
384 return ensureContextHandoff({
385 commandId: input.commandId,
386 threadId: input.threadId,
387 providerInstanceId: input.providerInstanceId,
388 capabilities: input.capabilities,
389 strategy: "full_thread_summary",
390 }).pipe(Effect.as("portable_context"));
391};
392
393export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
394 ensureQueuedMessages,
395 decideSteeringExecution,
396 ensureInterrupt,
397 ensureNativeFork,
398 decideForkExecution,
399 ensureRollback,
400 ensureContextHandoff,
401});