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
118/** A run that still owns the thread's provider turn. */
119export function isActiveRun(run: OrchestrationV2Run): boolean {
120 return (
121 run.status === "preparing" ||
122 run.status === "starting" ||
123 run.status === "running" ||
124 run.status === "waiting"
125 );
126}
127
128function providerTurnCapabilities(
129 projection: OrchestrationV2ThreadProjection,
130 run: OrchestrationV2Run,
131) {
132 const providerThread = projection.providerThreads.find(
133 (candidate) => candidate.id === run.providerThreadId,
134 );
135 const providerSession =
136 providerThread?.providerSessionId == null
137 ? undefined
138 : projection.providerSessions.find(
139 (candidate) => candidate.id === providerThread.providerSessionId,
140 );
141 return providerSession?.capabilities.turns;
142}
143
144function resolveDeliveryIntent(
145 projection: OrchestrationV2ThreadProjection,
146 requestedMode: MessageDispatchMode,
147 deliveryIntent?: "auto" | "steer" | "restart",
148): MessageDispatchMode {
149 if (deliveryIntent === undefined) return requestedMode;
150
151 const activeRun = projection.runs.findLast(isActiveRun);
152 if (activeRun === undefined) return { type: "start_immediately" };
153 if (deliveryIntent === "steer") {
154 return { type: "steer_active", targetRunId: activeRun.id };
155 }
156 if (deliveryIntent === "restart") {
157 return { type: "restart_active", targetRunId: activeRun.id };
158 }
159 // A run can be active before its provider turn starts or after it finishes.
160 // Queue automatic input in those gaps so steering cannot reject the message.
161 if (
162 activeRun.status === "preparing" ||
163 activeRun.status === "starting" ||
164 !projection.providerTurns.some(
165 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
166 )
167 ) {
168 return { type: "queue_after_active" };
169 }
170
171 const capabilities = providerTurnCapabilities(projection, activeRun);
172 if (capabilities?.supportsActiveSteering === true) {
173 return { type: "steer_active", targetRunId: activeRun.id };
174 }
175 if (capabilities?.supportsQueuedMessages === true) {
176 return { type: "queue_after_active" };
177 }
178 if (capabilities?.supportsSteeringByInterruptRestart === true) {
179 return { type: "restart_active", targetRunId: activeRun.id };
180 }
181 return { type: "queue_after_active" };
182}
183
184interface CapabilityCheckInput {
185 readonly commandId: CommandId;
186 readonly threadId: ThreadId;
187 readonly providerInstanceId: ProviderInstanceId;
188 readonly capabilities: OrchestrationV2ProviderCapabilities;
189}
190
191export interface CommandPolicyV2Shape {
192 readonly ensureQueuedMessages: (
193 input: CapabilityCheckInput,
194 ) => Effect.Effect<void, CommandPolicyV2Error>;
195 readonly decideSteeringExecution: (
196 input: CapabilityCheckInput & {
197 readonly forceRestart?: boolean;
198 },
199 ) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>;
200 readonly ensureInterrupt: (
201 input: CapabilityCheckInput,
202 ) => Effect.Effect<void, CommandPolicyV2Error>;
203 readonly ensureNativeFork: (
204 input: CapabilityCheckInput & {
205 readonly fromSpecificTurn: boolean;
206 },
207 ) => Effect.Effect<void, CommandPolicyV2Error>;
208 readonly decideForkExecution: (
209 input: CapabilityCheckInput & {
210 readonly sameProvider: boolean;
211 readonly hasStrongNativeSource: boolean;
212 readonly sourceRunStatus: OrchestrationV2Run["status"];
213 readonly fromSpecificTurn: boolean;
214 /** Later source runs are still active; providers cannot fork a thread mid-turn. */
215 readonly sourceBusy: boolean;
216 },
217 ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
218 readonly ensureRollback: (
219 input: CapabilityCheckInput,
220 ) => Effect.Effect<void, CommandPolicyV2Error>;
221 readonly ensureContextHandoff: (
222 input: CapabilityCheckInput & {
223 readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary";
224 },
225 ) => Effect.Effect<void, CommandPolicyV2Error>;
226}
227
228export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
229 "t3/orchestration-v2/CommandPolicy/CommandPolicyV2",
230) {}
231
232function unsupported(
233 input: CapabilityCheckInput,
234 capability: CommandPolicyCapability,
235 detail: string,
236) {
237 return new CommandPolicyCapabilityUnsupportedError({
238 commandId: input.commandId,
239 threadId: input.threadId,
240 providerInstanceId: input.providerInstanceId,
241 capability,
242 detail,
243 });
244}
245
246const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) =>
247 input.capabilities.turns.supportsQueuedMessages
248 ? Effect.void
249 : Effect.fail(
250 unsupported(
251 input,
252 "queued_messages",
253 "providerInstanceId does not support app-owned queued turns",
254 ),
255 );
256
257const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
258 if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {
259 return Effect.succeed("active_steering");
260 }
261 if (
262 input.capabilities.turns.supportsInterrupt &&
263 input.capabilities.turns.supportsSteeringByInterruptRestart
264 ) {
265 return Effect.succeed("interrupt_restart");
266 }
267 return Effect.fail(
268 unsupported(
269 input,
270 input.forceRestart || input.capabilities.turns.supportsInterrupt
271 ? "interrupt_restart_steering"
272 : "active_steering",
273 input.forceRestart
274 ? "providerInstanceId cannot satisfy a required interrupt-and-restart"
275 : "providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
276 ),
277 );
278};
279
280const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
281 input.capabilities.turns.supportsInterrupt
282 ? Effect.void
283 : Effect.fail(
284 unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
285 );
286
287const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
288 if (!input.capabilities.threads.canForkThread) {
289 return Effect.fail(
290 unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
291 );
292 }
293 if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
294 return Effect.fail(
295 unsupported(
296 input,
297 "fork_from_turn",
298 "providerInstanceId cannot fork from a specific completed turn",
299 ),
300 );
301 }
302 if (input.capabilities.identity.nativeThreadIds !== "strong") {
303 return Effect.fail(
304 unsupported(
305 input,
306 "native_fork",
307 "providerInstanceId does not expose strong native thread ids",
308 ),
309 );
310 }
311 return Effect.void;
312};
313
314const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
315 if (
316 !input.capabilities.threads.canRollbackThread ||
317 !input.capabilities.checkpointing.providerCanRollbackConversation
318 ) {
319 return Effect.fail(
320 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
321 );
322 }
323 if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
324 return Effect.fail(
325 unsupported(
326 input,
327 "rollback_snapshot",
328 "rollback must return a providerInstanceId thread snapshot",
329 ),
330 );
331 }
332 return Effect.void;
333};
334
335const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
336 if (!input.capabilities.context.canConsumeHandoffSummaries) {
337 return Effect.fail(
338 unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
339 );
340 }
341 if (!input.capabilities.context.acceptsSyntheticUserContext) {
342 return Effect.fail(
343 unsupported(
344 input,
345 "context_handoff",
346 "providerInstanceId cannot receive synthetic user context",
347 ),
348 );
349 }
350 if (
351 (input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
352 !input.capabilities.context.supportsDeltaHandoff
353 ) {
354 return Effect.fail(
355 unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
356 );
357 }
358 if (
359 input.strategy === "full_thread_summary" &&
360 !input.capabilities.context.supportsFullThreadHandoff
361 ) {
362 return Effect.fail(
363 unsupported(
364 input,
365 "context_handoff",
366 "providerInstanceId does not support full-thread handoff",
367 ),
368 );
369 }
370 return Effect.void;
371};
372
373const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => {
374 // Unsuccessful runs may lack native cursors; fork bounded transcripts to exclude later turns.
375 const canForkNatively =
376 (input.sourceRunStatus === "completed" || input.sourceRunStatus === "waiting") &&
377 input.sameProvider &&
378 input.hasStrongNativeSource &&
379 !input.sourceBusy &&
380 input.capabilities.threads.canForkThread &&
381 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
382 input.capabilities.identity.nativeThreadIds === "strong";
383
384 if (canForkNatively) {
385 return Effect.succeed("native_fork");
386 }
387
388 return ensureContextHandoff({
389 commandId: input.commandId,
390 threadId: input.threadId,
391 providerInstanceId: input.providerInstanceId,
392 capabilities: input.capabilities,
393 strategy: "full_thread_summary",
394 }).pipe(Effect.as("portable_context"));
395};
396
397export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
398 ensureQueuedMessages,
399 decideSteeringExecution,
400 ensureInterrupt,
401 ensureNativeFork,
402 decideForkExecution,
403 ensureRollback,
404 ensureContextHandoff,
405});