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

CommandPolicy.ts

471 lines15.7 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 { isSlashCommand } from "@t3tools/shared/composerTrigger";
14import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
15import * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Schema from "effect/Schema";
19​
20export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]);
21export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type;
22​
23export const ForkExecutionPolicyV2 = Schema.Literals(["native_fork", "portable_context"]);
24export type ForkExecutionPolicyV2 = typeof ForkExecutionPolicyV2.Type;
25​
26export const CommandPolicyCapability = Schema.Literals([
27 "queued_messages",
28 "active_steering",
29 "interrupt",
30 "interrupt_restart_steering",
31 "native_fork",
32 "fork_from_turn",
33 "rollback",
34 "rollback_snapshot",
35 "context_handoff",
36 "strong_terminal_status",
37]);
38export type CommandPolicyCapability = typeof CommandPolicyCapability.Type;
39​
40export class CommandPolicyCapabilityUnsupportedError extends Schema.TaggedError<CommandPolicyCapabilityUnsupportedError>()(
41 "CommandPolicyCapabilityUnsupportedError",
42 {
43 commandId: CommandId,
44 threadId: ThreadId,
45 providerInstanceId: ProviderInstanceId,
46 capability: CommandPolicyCapability,
47 detail: Schema.String,
48 },
49) {
50 override get message(): string {
51 return `${this.providerInstanceId} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`;
52 }
54​
55export const CommandPolicyV2Error = Schema.Union([CommandPolicyCapabilityUnsupportedError]);
56export type CommandPolicyV2Error = typeof CommandPolicyV2Error.Type;
57​
58type MessageDispatchMode = Extract<
59 OrchestrationV2Command,
60 { readonly type: "message.dispatch" }
61>["dispatchMode"];
62​
63/**
64 * A message that signs a provider account out at turn start, as `providerAuthLogout` does.
65 * With attachments the same text is an ordinary prompt.
66 */
67export function isProviderSignOutPrompt(message: {
68 readonly text: string;
69 readonly attachments: ReadonlyArray<ChatAttachment>;
70}): boolean {
71 return message.attachments.length === 0 && message.text.trim().toLowerCase() === "/logout";
73​
74export function isNativeMaintenanceCommand(message: {
75 readonly text: string;
76 readonly attachments: ReadonlyArray<ChatAttachment>;
77 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
78}): boolean {
79 return (
80 message.attachments.length === 0 &&
81 ["/compact", "/logout"].includes(message.text.trim().toLowerCase())
82 );
84​
85/**
86 * A goal command sent into active work stops that work when it starts or
87 * replaces goal work, or ends a goal that is driving the run.
88 */
89export function goalCommandStopsActiveRun(
90 command: OrchestrationV2GoalCommand,
91 goalStatus: OrchestrationV2ProviderGoalStatus | null,
92): boolean {
93 switch (command.type) {
94 case "set":
95 case "resume":
96 return true;
97 case "clear":
98 case "pause":
99 return goalStatus === "active";
100 case "show":
101 return false;
102 }
104​
105export function resolveMessageDispatch(
106 projection: OrchestrationV2ThreadProjection,
107 message: Pick<
108 Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
109 "dispatchMode" | "deliveryIntent" | "text" | "attachments"
110 >,
111): MessageDispatchMode {
112 const mode = resolveMessageDispatchIntent(
113 projection,
114 message.dispatchMode,
115 message.deliveryIntent,
116 );
117 // A provider runs a steered command in place of the turn's task, so commands wait.
118 return mode.type === "steer_active" && isSlashCommand(message)
119 ? { type: "queue_after_active" }
120 : mode;
122​
123/** How a message joins active work when it is free to steer. */
124export function resolveMessageDispatchIntent(
125 projection: OrchestrationV2ThreadProjection,
126 requestedMode: MessageDispatchMode,
127 deliveryIntent?: "auto" | "steer" | "restart",
128): MessageDispatchMode {
129 const mode = resolveDeliveryIntent(projection, requestedMode, deliveryIntent);
130 if (mode.type !== "steer_active") return mode;
131 // Compaction and sign-out cannot accept steers; queue follow-ups.
132 const target = projection.runs.find((run) => run.id === mode.targetRunId);
133 const targetMessage = projection.messages.find((message) => message.id === target?.userMessageId);
134 if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) {
135 return { type: "queue_after_active" };
136 }
137 // A provider that can neither steer nor restart its turn takes the message after the turn.
138 const turns =
139 target === undefined || !isActiveRun(target)
140 ? undefined
141 : providerTurnCapabilities(projection, target);
142 return turns !== undefined && !turns.supportsActiveSteering && providerSwitchWaitsForTurn(turns)
143 ? { type: "queue_after_active" }
144 : mode;
146​
147/** A run that still owns the thread's provider turn. */
148export function isActiveRun(run: OrchestrationV2Run): boolean {
149 return (
150 run.status === "preparing" ||
151 run.status === "starting" ||
152 run.status === "running" ||
153 run.status === "waiting"
154 );
156​
157/**
158 * Providers that key forks on native turn ids can only fork a busy source from a turn with one;
159 * a synthetic or missing boundary would fork the live conversation, including the running turn.
160 */
161export function canForkBusySourceNatively(
162 capabilities: OrchestrationV2ProviderCapabilities,
163 hasNativeTurnBoundary: boolean,
164): boolean {
165 return (
166 capabilities.threads.canForkWhileSourceRunning === true &&
167 (hasNativeTurnBoundary || !capabilities.turns.exposesNativeTurnId)
168 );
170​
171/** The run a follow-up to a finished child binds to: the latest active one, else the last that ran. */
172export function followUpOwnerRun(
173 runs: ReadonlyArray<OrchestrationV2Run>,
174): OrchestrationV2Run | null {
175 return (
176 runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ?? latestExecutedRun(runs)
177 );
179​
180/** A provider that cannot restart its turn for new input runs a provider switch after the turn. */
181export function providerSwitchWaitsForTurn(
182 turns: OrchestrationV2ProviderCapabilities["turns"],
183): boolean {
184 return (
185 turns.supportsQueuedMessages &&
186 !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart)
187 );
189​
190export function providerTurnCapabilities(
191 projection: OrchestrationV2ThreadProjection,
192 run: OrchestrationV2Run,
193) {
194 const providerThread = projection.providerThreads.find(
195 (candidate) => candidate.id === run.providerThreadId,
196 );
197 const providerSession =
198 providerThread?.providerSessionId == null
199 ? undefined
200 : projection.providerSessions.find(
201 (candidate) => candidate.id === providerThread.providerSessionId,
202 );
203 return providerSession?.capabilities.turns;
205​
206function resolveDeliveryIntent(
207 projection: OrchestrationV2ThreadProjection,
208 requestedMode: MessageDispatchMode,
209 deliveryIntent?: "auto" | "steer" | "restart",
210): MessageDispatchMode {
211 if (deliveryIntent === undefined) return requestedMode;
212​
213 const activeRun = projection.runs.findLast(isActiveRun);
214 if (activeRun === undefined) return { type: "start_immediately" };
215 if (deliveryIntent === "steer") {
216 return { type: "steer_active", targetRunId: activeRun.id };
217 }
218 if (deliveryIntent === "restart") {
219 return { type: "restart_active", targetRunId: activeRun.id };
220 }
221 // A run can be active before its provider turn starts or after it finishes.
222 // Queue automatic input in those gaps so steering cannot reject the message.
223 if (
224 activeRun.status === "preparing" ||
225 activeRun.status === "starting" ||
226 !projection.providerTurns.some(
227 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
228 )
229 ) {
230 return { type: "queue_after_active" };
231 }
232​
233 const capabilities = providerTurnCapabilities(projection, activeRun);
234 if (capabilities?.supportsActiveSteering === true) {
235 return { type: "steer_active", targetRunId: activeRun.id };
236 }
237 if (capabilities?.supportsQueuedMessages === true) {
238 return { type: "queue_after_active" };
239 }
240 if (capabilities?.supportsSteeringByInterruptRestart === true) {
241 return { type: "restart_active", targetRunId: activeRun.id };
242 }
243 return { type: "queue_after_active" };
245​
246interface CapabilityCheckInput {
247 readonly commandId: CommandId;
248 readonly threadId: ThreadId;
249 readonly providerInstanceId: ProviderInstanceId;
250 readonly capabilities: OrchestrationV2ProviderCapabilities;
252​
253export interface CommandPolicyV2Shape {
254 readonly ensureQueuedMessages: (
255 input: CapabilityCheckInput,
256 ) => Effect.Effect<void, CommandPolicyV2Error>;
257 readonly decideSteeringExecution: (
258 input: CapabilityCheckInput & {
259 readonly forceRestart?: boolean;
260 },
261 ) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>;
262 readonly ensureInterrupt: (
263 input: CapabilityCheckInput,
264 ) => Effect.Effect<void, CommandPolicyV2Error>;
265 readonly ensureNativeFork: (
266 input: CapabilityCheckInput & {
267 readonly fromSpecificTurn: boolean;
268 },
269 ) => Effect.Effect<void, CommandPolicyV2Error>;
270 readonly decideForkExecution: (
271 input: CapabilityCheckInput & {
272 readonly sameProvider: boolean;
273 readonly hasStrongNativeSource: boolean;
274 readonly hasNativeTurnBoundary: boolean;
275 readonly sourceRunStatus: OrchestrationV2Run["status"];
276 readonly fromSpecificTurn: boolean;
277 /** Later source runs are still active. */
278 readonly sourceBusy: boolean;
279 },
280 ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
281 readonly ensureRollback: (
282 input: CapabilityCheckInput,
283 ) => Effect.Effect<void, CommandPolicyV2Error>;
284 readonly ensureContextHandoff: (
285 input: CapabilityCheckInput & {
286 readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary";
287 },
288 ) => Effect.Effect<void, CommandPolicyV2Error>;
290​
291export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
292 "t3/orchestration-v2/CommandPolicy/CommandPolicyV2",
293) {}
294​
295function unsupported(
296 input: CapabilityCheckInput,
297 capability: CommandPolicyCapability,
298 detail: string,
299) {
300 return new CommandPolicyCapabilityUnsupportedError({
301 commandId: input.commandId,
302 threadId: input.threadId,
303 providerInstanceId: input.providerInstanceId,
304 capability,
305 detail,
306 });
308​
309const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) =>
310 input.capabilities.turns.supportsQueuedMessages
311 ? Effect.void
312 : Effect.fail(
313 unsupported(
314 input,
315 "queued_messages",
316 "providerInstanceId does not support app-owned queued turns",
317 ),
318 );
319​
320const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
321 if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {
322 return Effect.succeed("active_steering");
323 }
324 if (
325 input.capabilities.turns.supportsInterrupt &&
326 input.capabilities.turns.supportsSteeringByInterruptRestart
327 ) {
328 return Effect.succeed("interrupt_restart");
329 }
330 return Effect.fail(
331 unsupported(
332 input,
333 input.forceRestart || input.capabilities.turns.supportsInterrupt
334 ? "interrupt_restart_steering"
335 : "active_steering",
336 input.forceRestart
337 ? "providerInstanceId cannot satisfy a required interrupt-and-restart"
338 : "providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
339 ),
340 );
341};
342​
343const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
344 input.capabilities.turns.supportsInterrupt
345 ? Effect.void
346 : Effect.fail(
347 unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
348 );
349​
350const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
351 if (!input.capabilities.threads.canForkThread) {
352 return Effect.fail(
353 unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
354 );
355 }
356 if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
357 return Effect.fail(
358 unsupported(
359 input,
360 "fork_from_turn",
361 "providerInstanceId cannot fork from a specific completed turn",
362 ),
363 );
364 }
365 if (input.capabilities.identity.nativeThreadIds !== "strong") {
366 return Effect.fail(
367 unsupported(
368 input,
369 "native_fork",
370 "providerInstanceId does not expose strong native thread ids",
371 ),
372 );
373 }
374 return Effect.void;
375};
376​
377const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
378 // Without native truncation, the next turn replays the kept conversation as a handoff.
379 if (
380 !input.capabilities.threads.canRollbackThread ||
381 (!input.capabilities.checkpointing.providerCanRollbackConversation &&
382 !input.capabilities.context.canConsumeHandoffSummaries)
383 ) {
384 return Effect.fail(
385 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
386 );
387 }
388 if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
389 return Effect.fail(
390 unsupported(
391 input,
392 "rollback_snapshot",
393 "rollback must return a providerInstanceId thread snapshot",
394 ),
395 );
396 }
397 return Effect.void;
398};
399​
400const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
401 if (!input.capabilities.context.canConsumeHandoffSummaries) {
402 return Effect.fail(
403 unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
404 );
405 }
406 if (!input.capabilities.context.acceptsSyntheticUserContext) {
407 return Effect.fail(
408 unsupported(
409 input,
410 "context_handoff",
411 "providerInstanceId cannot receive synthetic user context",
412 ),
413 );
414 }
415 if (
416 (input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
417 !input.capabilities.context.supportsDeltaHandoff
418 ) {
419 return Effect.fail(
420 unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
421 );
422 }
423 if (
424 input.strategy === "full_thread_summary" &&
425 !input.capabilities.context.supportsFullThreadHandoff
426 ) {
427 return Effect.fail(
428 unsupported(
429 input,
430 "context_handoff",
431 "providerInstanceId does not support full-thread handoff",
432 ),
433 );
434 }
435 return Effect.void;
436};
437​
438const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => {
439 // Unsuccessful runs may lack native cursors; fork bounded transcripts to exclude later turns.
440 const canForkNatively =
441 (input.sourceRunStatus === "completed" || input.sourceRunStatus === "waiting") &&
442 input.sameProvider &&
443 input.hasStrongNativeSource &&
444 (!input.sourceBusy ||
445 canForkBusySourceNatively(input.capabilities, input.hasNativeTurnBoundary)) &&
446 input.capabilities.threads.canForkThread &&
447 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
448 input.capabilities.identity.nativeThreadIds === "strong";
449​
450 if (canForkNatively) {
451 return Effect.succeed("native_fork");
452 }
453​
454 return ensureContextHandoff({
455 commandId: input.commandId,
456 threadId: input.threadId,
457 providerInstanceId: input.providerInstanceId,
458 capabilities: input.capabilities,
459 strategy: "full_thread_summary",
460 }).pipe(Effect.as("portable_context"));
461};
462​
463export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
464 ensureQueuedMessages,
465 decideSteeringExecution,
466 ensureInterrupt,
467 ensureNativeFork,
468 decideForkExecution,
469 ensureRollback,
470 ensureContextHandoff,
471});