Open History to see the last commit
1import {
2 isRuntimeModeAbove,
3 managedRuntimeModeCeilingMessage,
4 ModelSelection,
5 OrchestrationV2AppThread,
6 ProjectId,
7 ProviderInstanceId,
8 RuntimeMode,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16
17import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
18import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
19import * as ServerSettings from "../serverSettings.ts";
20import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts";
21import * as ProjectStore from "./ProjectStore.ts";
22
23export class RuntimePolicyResolveError extends Schema.TaggedError<RuntimePolicyResolveError>()(
24 "RuntimePolicyResolveError",
25 {
26 projectId: ProjectId,
27 providerInstanceId: ProviderInstanceId,
28 cause: Schema.optional(Schema.Defect()),
29 },
30) {
31 override get message(): string {
32 return `Failed to resolve runtime policy for provider instance ${this.providerInstanceId} in project ${this.projectId}.`;
33 }
34}
35
36/**
37 * A turn would start in a mode above the policy's ceiling. The orchestrator refuses those when
38 * they are dispatched; this catches the ones it never saw, such as a run resumed after a restart
39 * on a thread whose mode predates the policy.
40 */
41export class RuntimePolicyAboveCeilingError extends Schema.TaggedError<RuntimePolicyAboveCeilingError>()(
42 "RuntimePolicyAboveCeilingError",
43 {
44 threadId: ThreadId,
45 runtimeMode: RuntimeMode,
46 maxRuntimeMode: RuntimeMode,
47 organization: Schema.String,
48 },
49) {
50 override get message(): string {
51 return `${managedRuntimeModeCeilingMessage(this.organization, this.maxRuntimeMode)} Switch this thread's mode to continue.`;
52 }
53}
54
55export const isRuntimePolicyAboveCeilingError = Schema.is(RuntimePolicyAboveCeilingError);
56
57export const RuntimePolicyV2Error = Schema.Union([
58 RuntimePolicyResolveError,
59 RuntimePolicyAboveCeilingError,
60]);
61export type RuntimePolicyV2Error = typeof RuntimePolicyV2Error.Type;
62
63export const RuntimePolicyV2Override = Schema.Struct({
64 cwd: Schema.optional(Schema.String),
65 approvalPolicy: Schema.optional(Schema.Unknown),
66 sandboxPolicy: Schema.optional(Schema.Unknown),
67 reasoningEffort: Schema.optional(Schema.String),
68});
69export type RuntimePolicyV2Override = typeof RuntimePolicyV2Override.Type;
70
71export interface RuntimePolicyV2Shape {
72 readonly resolve: (input: {
73 readonly thread: OrchestrationV2AppThread;
74 readonly modelSelection: ModelSelection;
75 }) => Effect.Effect<ProviderAdapter.ProviderAdapterV2RuntimePolicy, RuntimePolicyV2Error>;
76}
77
78export class RuntimePolicyV2 extends Context.Service<RuntimePolicyV2, RuntimePolicyV2Shape>()(
79 "t3/orchestration-v2/RuntimePolicy/RuntimePolicyV2",
80) {}
81
82export function providerRuntimeMode(
83 runtimeMode: RuntimeMode,
84 supportedRuntimeModes: ReadonlyArray<RuntimeMode> | undefined,
85): RuntimeMode {
86 return supportedRuntimeModes === undefined ||
87 supportedRuntimeModes.length === 0 ||
88 supportedRuntimeModes.includes(runtimeMode)
89 ? runtimeMode
90 : "approval-required";
91}
92
93const refuseAboveCeiling = (
94 managedPolicy: ServerSettings.ServerSettingsService["Service"]["managedPolicy"],
95 thread: OrchestrationV2AppThread,
96) => {
97 const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
98 return managedPolicy !== undefined &&
99 maxRuntimeMode !== undefined &&
100 isRuntimeModeAbove(thread.runtimeMode, maxRuntimeMode)
101 ? Effect.fail(
102 new RuntimePolicyAboveCeilingError({
103 threadId: thread.id,
104 runtimeMode: thread.runtimeMode,
105 maxRuntimeMode,
106 organization: managedPolicy.organization,
107 }),
108 )
109 : Effect.void;
110};
111
112/** Lays the policy's ceiling over another runtime policy, as `layerFromProjectStore` does. */
113export const layerEnforcingCeiling: Layer.Layer<
114 RuntimePolicyV2,
115 never,
116 RuntimePolicyV2 | ServerSettings.ServerSettingsService
117> = Layer.effect(
118 RuntimePolicyV2,
119 Effect.gen(function* () {
120 const base = yield* RuntimePolicyV2;
121 const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
122 return RuntimePolicyV2.of({
123 resolve: Effect.fn("RuntimePolicyV2.resolveWithinCeiling")(function* (input) {
124 yield* refuseAboveCeiling(managedPolicy, input.thread);
125 return yield* base.resolve(input);
126 }),
127 });
128 }),
129);
130
131export const layerFromProjectStore: Layer.Layer<
132 RuntimePolicyV2,
133 never,
134 | ProjectStore.ProjectStoreV2
135 | ProviderInstanceRegistry.ProviderInstanceRegistry
136 | ServerSettings.ServerSettingsService
137 | WorkspaceFolders.WorkspaceFolders
138> = Layer.effect(
139 RuntimePolicyV2,
140 Effect.gen(function* () {
141 const projects = yield* ProjectStore.ProjectStoreV2;
142 const workspaceFolders = yield* WorkspaceFolders.WorkspaceFolders;
143 const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
144 // The same ceiling the orchestrator enforces, fixed for the server's life.
145 const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
146 const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
147 return RuntimePolicyV2.of({
148 resolve: Effect.fn("RuntimePolicyV2.resolve")(function* (input) {
149 yield* refuseAboveCeiling(managedPolicy, input.thread);
150 const instance = yield* providerInstances.getInstance(input.modelSelection.instanceId);
151 const supportedRuntimeModes =
152 instance === undefined
153 ? undefined
154 : (yield* instance.snapshot.getSnapshot).supportedRuntimeModes;
155 const cwd =
156 input.thread.worktreePath ??
157 (yield* projects.get(input.thread.projectId).pipe(
158 Effect.mapError(
159 (cause) =>
160 new RuntimePolicyResolveError({
161 projectId: input.thread.projectId,
162 providerInstanceId: input.modelSelection.instanceId,
163 cause,
164 }),
165 ),
166 Effect.flatMap(
167 Option.match({
168 onNone: () =>
169 Effect.fail(
170 new RuntimePolicyResolveError({
171 projectId: input.thread.projectId,
172 providerInstanceId: input.modelSelection.instanceId,
173 cause: "Project not found.",
174 }),
175 ),
176 onSome: (project) => Effect.succeed(project.workspaceRoot),
177 }),
178 ),
179 ));
180 // The turn can still run in its own cwd, as a single-folder thread does.
181 const workspace = yield* workspaceFolders
182 .forThread({
183 projectId: input.thread.projectId,
184 worktreePath: input.thread.worktreePath,
185 })
186 .pipe(
187 Effect.catch((cause) =>
188 Effect.logWarning("Could not resolve the thread's tracked folders.", cause).pipe(
189 Effect.as(undefined),
190 ),
191 ),
192 );
193 return ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
194 runtimeMode: providerRuntimeMode(input.thread.runtimeMode, supportedRuntimeModes),
195 interactionMode: input.thread.interactionMode,
196 cwd,
197 ...(maxRuntimeMode === undefined ? {} : { maxRuntimeMode }),
198 ...(workspace === undefined || workspace.folders.length === 0 ? {} : { workspace }),
199 });
200 }),
201 });
202 }),
203);
204
205export function layerWithOverride(
206 override: RuntimePolicyV2Override,
207): Layer.Layer<RuntimePolicyV2, never, RuntimePolicyV2> {
208 return Layer.effect(
209 RuntimePolicyV2,
210 Effect.gen(function* () {
211 const base = yield* RuntimePolicyV2;
212 return {
213 resolve: (input) =>
214 base.resolve(input).pipe(
215 Effect.map((policy) =>
216 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
217 ...policy,
218 ...(override.cwd === undefined ? {} : { cwd: override.cwd }),
219 ...(override.approvalPolicy === undefined
220 ? {}
221 : { approvalPolicy: override.approvalPolicy }),
222 ...(override.sandboxPolicy === undefined
223 ? {}
224 : { sandboxPolicy: override.sandboxPolicy }),
225 ...(override.reasoningEffort === undefined
226 ? {}
227 : { reasoningEffort: override.reasoningEffort }),
228 }),
229 ),
230 ),
231 } satisfies RuntimePolicyV2Shape;
232 }),
233 );
234}