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

CommandPolicy.ts

380 lines12.3 KB

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