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

RuntimePolicy.ts

244 lines8.7 KB

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 }
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 }
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>;
77​
78export class RuntimePolicyV2 extends Context.Service<RuntimePolicyV2, RuntimePolicyV2Shape>()(
79 "t3/orchestration-v2/RuntimePolicy/RuntimePolicyV2",
80) {}
81​
82export const layer: Layer.Layer<RuntimePolicyV2> = Layer.succeed(RuntimePolicyV2, {
83 resolve: Effect.fn("RuntimePolicyV2.resolve")(function (input) {
84 return Effect.succeed({
85 runtimeMode: input.thread.runtimeMode,
86 interactionMode: input.thread.interactionMode,
87 cwd: input.thread.worktreePath,
88 });
89 }),
90});
91​
92export function providerRuntimeMode(
93 runtimeMode: RuntimeMode,
94 supportedRuntimeModes: ReadonlyArray<RuntimeMode> | undefined,
95): RuntimeMode {
96 return supportedRuntimeModes === undefined ||
97 supportedRuntimeModes.length === 0 ||
98 supportedRuntimeModes.includes(runtimeMode)
99 ? runtimeMode
100 : "approval-required";
102​
103const refuseAboveCeiling = (
104 managedPolicy: ServerSettings.ServerSettingsService["Service"]["managedPolicy"],
105 thread: OrchestrationV2AppThread,
106) => {
107 const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
108 return managedPolicy !== undefined &&
109 maxRuntimeMode !== undefined &&
110 isRuntimeModeAbove(thread.runtimeMode, maxRuntimeMode)
111 ? Effect.fail(
112 new RuntimePolicyAboveCeilingError({
113 threadId: thread.id,
114 runtimeMode: thread.runtimeMode,
115 maxRuntimeMode,
116 organization: managedPolicy.organization,
117 }),
118 )
119 : Effect.void;
120};
121​
122/** Lays the policy's ceiling over another runtime policy, as `layerFromProjectStore` does. */
123export const layerEnforcingCeiling: Layer.Layer<
124 RuntimePolicyV2,
125 never,
126 RuntimePolicyV2 | ServerSettings.ServerSettingsService
127> = Layer.effect(
128 RuntimePolicyV2,
129 Effect.gen(function* () {
130 const base = yield* RuntimePolicyV2;
131 const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
132 return RuntimePolicyV2.of({
133 resolve: Effect.fn("RuntimePolicyV2.resolveWithinCeiling")(function* (input) {
134 yield* refuseAboveCeiling(managedPolicy, input.thread);
135 return yield* base.resolve(input);
136 }),
137 });
138 }),
139);
140​
141export const layerFromProjectStore: Layer.Layer<
142 RuntimePolicyV2,
143 never,
144 | ProjectStore.ProjectStoreV2
145 | ProviderInstanceRegistry.ProviderInstanceRegistry
146 | ServerSettings.ServerSettingsService
147 | WorkspaceFolders.WorkspaceFolders
148> = Layer.effect(
149 RuntimePolicyV2,
150 Effect.gen(function* () {
151 const projects = yield* ProjectStore.ProjectStoreV2;
152 const workspaceFolders = yield* WorkspaceFolders.WorkspaceFolders;
153 const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
154 // The same ceiling the orchestrator enforces, fixed for the server's life.
155 const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
156 const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
157 return RuntimePolicyV2.of({
158 resolve: Effect.fn("RuntimePolicyV2.resolve")(function* (input) {
159 yield* refuseAboveCeiling(managedPolicy, input.thread);
160 const instance = yield* providerInstances.getInstance(input.modelSelection.instanceId);
161 const supportedRuntimeModes =
162 instance === undefined
163 ? undefined
164 : (yield* instance.snapshot.getSnapshot).supportedRuntimeModes;
165 const cwd =
166 input.thread.worktreePath ??
167 (yield* projects.get(input.thread.projectId).pipe(
168 Effect.mapError(
169 (cause) =>
170 new RuntimePolicyResolveError({
171 projectId: input.thread.projectId,
172 providerInstanceId: input.modelSelection.instanceId,
173 cause,
174 }),
175 ),
176 Effect.flatMap(
177 Option.match({
178 onNone: () =>
179 Effect.fail(
180 new RuntimePolicyResolveError({
181 projectId: input.thread.projectId,
182 providerInstanceId: input.modelSelection.instanceId,
183 cause: "Project not found.",
184 }),
185 ),
186 onSome: (project) => Effect.succeed(project.workspaceRoot),
187 }),
188 ),
189 ));
190 // The turn can still run in its own cwd, as a single-folder thread does.
191 const workspace = yield* workspaceFolders
192 .forThread({
193 projectId: input.thread.projectId,
194 worktreePath: input.thread.worktreePath,
195 })
196 .pipe(
197 Effect.catch((cause) =>
198 Effect.logWarning("Could not resolve the thread's tracked folders.", cause).pipe(
199 Effect.as(undefined),
200 ),
201 ),
202 );
203 return ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
204 runtimeMode: providerRuntimeMode(input.thread.runtimeMode, supportedRuntimeModes),
205 interactionMode: input.thread.interactionMode,
206 cwd,
207 ...(maxRuntimeMode === undefined ? {} : { maxRuntimeMode }),
208 ...(workspace === undefined || workspace.folders.length === 0 ? {} : { workspace }),
209 });
210 }),
211 });
212 }),
213);
214​
215export function layerWithOverride(
216 override: RuntimePolicyV2Override,
217): Layer.Layer<RuntimePolicyV2, never, RuntimePolicyV2> {
218 return Layer.effect(
219 RuntimePolicyV2,
220 Effect.gen(function* () {
221 const base = yield* RuntimePolicyV2;
222 return {
223 resolve: (input) =>
224 base.resolve(input).pipe(
225 Effect.map((policy) =>
226 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
227 ...policy,
228 ...(override.cwd === undefined ? {} : { cwd: override.cwd }),
229 ...(override.approvalPolicy === undefined
230 ? {}
231 : { approvalPolicy: override.approvalPolicy }),
232 ...(override.sandboxPolicy === undefined
233 ? {}
234 : { sandboxPolicy: override.sandboxPolicy }),
235 ...(override.reasoningEffort === undefined
236 ? {}
237 : { reasoningEffort: override.reasoningEffort }),
238 }),
239 ),
240 ),
241 } satisfies RuntimePolicyV2Shape;
242 }),
243 );