+36
![github-actions[bot]](/assets/img/avatar_default.png)








Julius Marminge
maria-rcks
Bilal Bakr
shivam
Vitalii Yehorov
Jake Leventhal
Claude Opus 5
Alex Southwell
github-actions[bot]
Nicholas Wasmiller
PB
Exotic
Yash Singh
Devin
Theo Browne
Gabriel De Andrade
Dara Adedeji
scratchyone
Dominic Roy
chukfinley
Primož Ajdišek
benthecarman
NaveDanan
aaditagrawal
Aditya Garud
Nick Anisimov
MacKinley Smith
Yordis Prieto
t3-code[bot]
AKolenda
Guillermo Casanova
Otavio Salvador
Shirish Pothi
Ishaan Kothari
Bob Fowler
Anton Bezdenezhnykh
ValeraZSD
Ephraim
Ryan Ilano
Alex
maco
Cursor
Tristan Knight
PR Batch Tester
oliver
kamkm
de34391427
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Bilal Bakr <[email protected]> Co-authored-by: shivam <[email protected]> Co-authored-by: Vitalii Yehorov <[email protected]> Co-authored-by: Jake Leventhal <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Alex Southwell <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Nicholas Wasmiller <[email protected]> Co-authored-by: PB <[email protected]> Co-authored-by: Exotic <[email protected]> Co-authored-by: Yash Singh <[email protected]> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Theo Browne <[email protected]> Co-authored-by: Gabriel De Andrade <[email protected]> Co-authored-by: Dara Adedeji <[email protected]> Co-authored-by: scratchyone <[email protected]> Co-authored-by: Dominic Roy <[email protected]> Co-authored-by: chukfinley <[email protected]> Co-authored-by: Primož Ajdišek <[email protected]> Co-authored-by: benthecarman <[email protected]> Co-authored-by: NaveDanan <[email protected]> Co-authored-by: aaditagrawal <[email protected]> Co-authored-by: Aditya Garud <[email protected]> Co-authored-by: Nick Anisimov <[email protected]> Co-authored-by: MacKinley Smith <[email protected]> Co-authored-by: Yordis Prieto <[email protected]> Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com> Co-authored-by: AKolenda <[email protected]> Co-authored-by: Guillermo Casanova <[email protected]> Co-authored-by: Otavio Salvador <[email protected]> Co-authored-by: Shirish Pothi <[email protected]> Co-authored-by: Ishaan Kothari <[email protected]> Co-authored-by: Bob Fowler <[email protected]> Co-authored-by: Anton Bezdenezhnykh <[email protected]> Co-authored-by: ValeraZSD <[email protected]> Co-authored-by: Ephraim <[email protected]> Co-authored-by: Ryan Ilano <[email protected]> Co-authored-by: Alex <[email protected]> Co-authored-by: maco <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Tristan Knight <[email protected]> Co-authored-by: PR Batch Tester <[email protected]> Co-authored-by: oliver <[email protected]> Co-authored-by: kamkm <[email protected]> Signed-off-by: Yordis Prieto <[email protected]>
351 lines
14 KiB
TypeScript
351 lines
14 KiB
TypeScript
import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
|
|
import {
|
|
MessageId,
|
|
ProviderSessionId,
|
|
ProviderThreadId,
|
|
ProviderTurnId,
|
|
RunAttemptId,
|
|
ThreadId,
|
|
} from "@t3tools/contracts";
|
|
import * as Context from "effect/Context";
|
|
import * as Effect from "effect/Effect";
|
|
import * as Layer from "effect/Layer";
|
|
import * as Option from "effect/Option";
|
|
import * as Schema from "effect/Schema";
|
|
|
|
import * as ProjectionStore from "./ProjectionStore.ts";
|
|
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
|
|
|
|
const yieldToRuntime = Effect.yieldNow.pipe(
|
|
Effect.andThen(
|
|
Effect.promise(
|
|
() =>
|
|
new Promise<void>((resolve) => {
|
|
setImmediate(resolve);
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
export class ProviderTurnControlError extends Schema.TaggedError<ProviderTurnControlError>()(
|
|
"ProviderTurnControlError",
|
|
{
|
|
threadId: ThreadId,
|
|
operation: Schema.Literals(["interrupt", "restart", "steer"]),
|
|
providerTurnId: ProviderTurnId,
|
|
turnCompleted: Schema.optional(Schema.Boolean),
|
|
cause: Schema.optional(Schema.Defect()),
|
|
},
|
|
) {}
|
|
|
|
const isProviderTurnControlError = Schema.is(ProviderTurnControlError);
|
|
|
|
export interface ProviderTurnControlServiceV2Shape {
|
|
readonly interrupt: (input: {
|
|
readonly threadId: ThreadId;
|
|
readonly providerSessionId: ProviderSessionId;
|
|
readonly providerThreadId: ProviderThreadId;
|
|
readonly providerTurnId: ProviderTurnId;
|
|
}) => Effect.Effect<void, ProviderTurnControlError>;
|
|
readonly steer: (input: {
|
|
readonly threadId: ThreadId;
|
|
readonly providerSessionId: ProviderSessionId;
|
|
readonly providerThreadId: ProviderThreadId;
|
|
readonly providerTurnId: ProviderTurnId;
|
|
readonly messageId: MessageId;
|
|
}) => Effect.Effect<void, ProviderTurnControlError>;
|
|
readonly interruptAndAwaitTerminal: (input: {
|
|
readonly threadId: ThreadId;
|
|
readonly providerSessionId: ProviderSessionId;
|
|
readonly replacementProviderSessionId?: ProviderSessionId;
|
|
readonly providerThreadId: ProviderThreadId;
|
|
readonly providerTurnId: ProviderTurnId;
|
|
readonly interruptedAttemptId: RunAttemptId;
|
|
}) => Effect.Effect<void, ProviderTurnControlError>;
|
|
}
|
|
|
|
export class ProviderTurnControlServiceV2 extends Context.Service<
|
|
ProviderTurnControlServiceV2,
|
|
ProviderTurnControlServiceV2Shape
|
|
>()("t3/orchestration-v2/ProviderTurnControlService/ProviderTurnControlServiceV2") {}
|
|
|
|
export const layer: Layer.Layer<
|
|
ProviderTurnControlServiceV2,
|
|
never,
|
|
ProjectionStore.ProjectionStoreV2 | ProviderSessionManager.ProviderSessionManagerV2
|
|
> = Layer.effect(
|
|
ProviderTurnControlServiceV2,
|
|
Effect.gen(function* () {
|
|
const projections = yield* ProjectionStore.ProjectionStoreV2;
|
|
const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
|
|
|
|
const load = (input: {
|
|
readonly threadId: ThreadId;
|
|
readonly providerSessionId: ProviderSessionId;
|
|
readonly replacementProviderSessionId?: ProviderSessionId;
|
|
readonly providerThreadId: ProviderThreadId;
|
|
readonly providerTurnId: ProviderTurnId;
|
|
readonly operation: "interrupt" | "restart" | "steer";
|
|
readonly messageId?: MessageId;
|
|
}) =>
|
|
Effect.gen(function* () {
|
|
const context = yield* projections.getProviderControlContext(input.threadId, input);
|
|
const { providerThread, providerTurn } = context;
|
|
const targetsRecordedSession =
|
|
providerThread?.providerSessionId === input.providerSessionId;
|
|
const targetsCommittedReplacement =
|
|
input.operation === "restart" &&
|
|
input.replacementProviderSessionId !== undefined &&
|
|
providerThread?.providerSessionId === input.replacementProviderSessionId;
|
|
if (
|
|
providerThread === undefined ||
|
|
providerTurn === undefined ||
|
|
(!targetsRecordedSession && !targetsCommittedReplacement) ||
|
|
providerTurn.providerThreadId !== providerThread.id
|
|
) {
|
|
return yield* new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: input.operation,
|
|
providerTurnId: input.providerTurnId,
|
|
cause: "The recorded provider execution target is no longer valid.",
|
|
});
|
|
}
|
|
// A restart-session command commits the replacement binding before its
|
|
// process-bound effect runs. The old live runtime must still receive
|
|
// the interrupt, but only when the projection matches the exact
|
|
// replacement captured by that same durable effect.
|
|
const interruptProviderThread = targetsRecordedSession
|
|
? providerThread
|
|
: { ...providerThread, providerSessionId: input.providerSessionId };
|
|
if (providerTurn.status !== "running") {
|
|
if (input.operation === "steer") {
|
|
return yield* new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: "steer",
|
|
providerTurnId: input.providerTurnId,
|
|
turnCompleted: providerTurn.status === "completed",
|
|
cause: "The provider turn ended before the steering message was delivered.",
|
|
});
|
|
}
|
|
return {
|
|
context,
|
|
providerThread: interruptProviderThread,
|
|
providerTurn,
|
|
session: Option.none(),
|
|
};
|
|
}
|
|
const session = yield* sessions.get(input.providerSessionId);
|
|
if (Option.isNone(session)) {
|
|
// Interrupt/restart against a already-released session must not fail
|
|
// the durable effect (and retry 5x). The turn may still look running
|
|
// in projection until recovery/finalization; there is no live adapter
|
|
// to interrupt.
|
|
if (input.operation === "interrupt" || input.operation === "restart") {
|
|
yield* Effect.logWarning(
|
|
"Provider interrupt/restart found no live session; treating as already stopped",
|
|
{
|
|
threadId: input.threadId,
|
|
operation: input.operation,
|
|
providerSessionId: input.providerSessionId,
|
|
providerTurnId: input.providerTurnId,
|
|
providerTurnStatus: providerTurn.status,
|
|
},
|
|
);
|
|
return {
|
|
context,
|
|
providerThread: interruptProviderThread,
|
|
providerTurn,
|
|
session: Option.none(),
|
|
};
|
|
}
|
|
return yield* new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: input.operation,
|
|
providerTurnId: input.providerTurnId,
|
|
cause: `Provider session ${input.providerSessionId} is not active.`,
|
|
});
|
|
}
|
|
return { context, providerThread: interruptProviderThread, providerTurn, session };
|
|
});
|
|
|
|
return ProviderTurnControlServiceV2.of({
|
|
interrupt: (input) =>
|
|
Effect.gen(function* () {
|
|
const loaded = yield* load({ ...input, operation: "interrupt" });
|
|
const session = Option.isSome(loaded.session)
|
|
? loaded.session
|
|
: yield* sessions.get(input.providerSessionId);
|
|
if (Option.isNone(session)) return;
|
|
// A settled turn reaches its adapter too: only the adapter knows
|
|
// whether it still runs work for the thread, and each one either
|
|
// stops it or reports there is nothing left to stop. Background work
|
|
// the projection still shows is settled by the orchestrator after.
|
|
yield* session.value.interruptTurn({
|
|
providerThread: loaded.providerThread,
|
|
providerTurnId: loaded.providerTurn.id,
|
|
requestRuntimeRestart: true,
|
|
});
|
|
}).pipe(
|
|
Effect.mapError((cause) =>
|
|
isProviderTurnControlError(cause)
|
|
? cause
|
|
: new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: "interrupt",
|
|
providerTurnId: input.providerTurnId,
|
|
cause,
|
|
}),
|
|
),
|
|
),
|
|
interruptAndAwaitTerminal: (input) =>
|
|
Effect.gen(function* () {
|
|
const loaded = yield* load({ ...input, operation: "restart" });
|
|
if (Option.isNone(loaded.session)) {
|
|
// No live adapter: nothing can emit a terminal provider-turn update
|
|
// from interrupt. Do not poll for projection terminalization or the
|
|
// restart effect stalls; let detach/start proceed.
|
|
if (loaded.providerTurn.status === "running") {
|
|
yield* Effect.logWarning(
|
|
"Provider restart interrupt skipped; no live session for a still-projected running turn",
|
|
{
|
|
threadId: input.threadId,
|
|
providerSessionId: input.providerSessionId,
|
|
providerTurnId: input.providerTurnId,
|
|
},
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
|
|
yield* loaded.session.value.interruptTurn({
|
|
providerThread: loaded.providerThread,
|
|
providerTurnId: loaded.providerTurn.id,
|
|
});
|
|
|
|
for (let remaining = 1_000; remaining > 0; remaining -= 1) {
|
|
const { providerTurn, attempt } = yield* projections.getProviderControlContext(
|
|
input.threadId,
|
|
{
|
|
providerThreadId: input.providerThreadId,
|
|
providerTurnId: input.providerTurnId,
|
|
attemptId: input.interruptedAttemptId,
|
|
},
|
|
);
|
|
if (
|
|
providerTurn !== undefined &&
|
|
providerTurn.status !== "running" &&
|
|
attempt !== undefined &&
|
|
attempt.status !== "running"
|
|
) {
|
|
return;
|
|
}
|
|
// Provider terminal events are projected on a detached ingestion
|
|
// fiber. Yield through the Node event loop instead of sleeping on
|
|
// Effect's clock so deterministic runtimes cannot deadlock a
|
|
// command that is waiting for that projection.
|
|
yield* yieldToRuntime;
|
|
}
|
|
return yield* new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: "restart",
|
|
providerTurnId: input.providerTurnId,
|
|
cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
|
|
});
|
|
}).pipe(
|
|
Effect.mapError((cause) =>
|
|
isProviderTurnControlError(cause)
|
|
? cause
|
|
: new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: "restart",
|
|
providerTurnId: input.providerTurnId,
|
|
cause,
|
|
}),
|
|
),
|
|
),
|
|
steer: (input) =>
|
|
Effect.gen(function* () {
|
|
const context = yield* projections.getProviderControlContext(input.threadId, input);
|
|
const ownership = context.message?.delegatedCompletion;
|
|
if (ownership !== undefined) {
|
|
const projection = yield* projections.getThreadRecords(input.threadId, ["runs"], {
|
|
runIds: [ownership.parentRunId],
|
|
});
|
|
const cohort = projection.runs.find(
|
|
(run) => run.id === ownership.parentRunId,
|
|
)?.delegatedCompletion;
|
|
if (
|
|
cohort?.disposition !== "open" ||
|
|
cohort.delivery?.messageId !== input.messageId ||
|
|
cohort.delivery.generation !== ownership.generation ||
|
|
cohort.delivery.taskIds.length === 0
|
|
)
|
|
return;
|
|
}
|
|
const loaded = yield* load({ ...input, operation: "steer" });
|
|
if (Option.isNone(loaded.session)) return;
|
|
const { message, run } = loaded.context;
|
|
if (message === undefined || run === undefined) {
|
|
return yield* new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: "steer",
|
|
providerTurnId: input.providerTurnId,
|
|
cause: "The persisted steering message or target run is missing.",
|
|
});
|
|
}
|
|
yield* loaded.session.value
|
|
.steerTurn({
|
|
threadId: input.threadId,
|
|
runId: run.id,
|
|
providerThread: loaded.providerThread,
|
|
providerTurnId: loaded.providerTurn.id,
|
|
message: {
|
|
messageId: message.id,
|
|
text: projectComposerContextForProvider({
|
|
text: message.text,
|
|
records: message.context?.records ?? [],
|
|
}),
|
|
attachments: message.attachments,
|
|
createdBy: message.createdBy,
|
|
creationSource: message.creationSource,
|
|
...(message.scheduledTaskId === undefined
|
|
? {}
|
|
: { scheduledTaskId: message.scheduledTaskId }),
|
|
...(message.senderThreadId === undefined
|
|
? {}
|
|
: { senderThreadId: message.senderThreadId }),
|
|
},
|
|
})
|
|
.pipe(
|
|
Effect.catch((cause) =>
|
|
Effect.gen(function* () {
|
|
const current = yield* projections.getProviderControlContext(
|
|
input.threadId,
|
|
input,
|
|
);
|
|
return yield* new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: "steer",
|
|
providerTurnId: input.providerTurnId,
|
|
turnCompleted: current.providerTurn?.status === "completed",
|
|
cause,
|
|
});
|
|
}),
|
|
),
|
|
);
|
|
}).pipe(
|
|
Effect.mapError((cause) =>
|
|
isProviderTurnControlError(cause)
|
|
? cause
|
|
: new ProviderTurnControlError({
|
|
threadId: input.threadId,
|
|
operation: "steer",
|
|
providerTurnId: input.providerTurnId,
|
|
cause,
|
|
}),
|
|
),
|
|
),
|
|
});
|
|
}),
|
|
);
|