Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/server/scripts/migrate-dev-db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
[1, "ProjectRuntime"],
[2, "DevelopmentProfiles"],
[3, "TaskHandoffState"],
[4, "RuntimeRouting"],
],
);
assert.deepStrictEqual(state.audit, []);
Expand Down Expand Up @@ -385,14 +386,14 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
};
}),
);
// Reconciled history keeps its original timestamps; Task/Handoff state is new work and
// runs as the third fork migration on top of it.
// Reconciled history keeps its original timestamps; newer fork work runs on top of it.
assert.deepStrictEqual(
state.fork.map((row) => [row.migration_id, row.name]),
[
[1, "ProjectRuntime"],
[2, "DevelopmentProfiles"],
[3, "TaskHandoffState"],
[4, "RuntimeRouting"],
],
);
assert.deepStrictEqual(
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export const RPC_REQUIRED_SCOPES = {
[PROJECT_RUNTIME_RPC_METHODS.readTask]: AuthOrchestrationReadScope,
[PROJECT_RUNTIME_RPC_METHODS.listHandoffs]: AuthOrchestrationReadScope,
[PROJECT_RUNTIME_RPC_METHODS.readHandoff]: AuthOrchestrationReadScope,
[PROJECT_RUNTIME_RPC_METHODS.readRouting]: AuthOrchestrationReadScope,
[PROJECT_RUNTIME_RPC_METHODS.resolveRoute]: AuthOrchestrationReadScope,

[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
DevelopmentProfileProjectNotFoundError,
EffectiveProjectInstructions,
ProjectId,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
Expand Down Expand Up @@ -507,3 +508,61 @@ it.effect(
assert.deepEqual(yield* service.getAssignment(projectA), assignment);
}).pipe(Effect.provide(layerTest)),
);

it.effect("writes instructions and routing under one profile revision", () =>
Effect.gen(function* () {
const service = yield* DevelopmentProfileService.DevelopmentProfileService;
const implementation = {
role: "implementation" as const,
candidates: [{ providerInstanceId: ProviderInstanceId.make("codex"), model: "gpt-6" }],
fallback: "inherit" as const,
};
const created = yield* service.create(
{ name: "Routing policy", instructions: "Use the main model" },
actor,
);
assert.deepEqual(created.routing, { roleRoutes: [] });

const updated = yield* service.update(
{
profileId: created.profileId,
name: "Routing policy",
instructions: "Use the routed model",
routing: { roleRoutes: [implementation] },
expectedRevision: 1,
},
actor,
);
assert.equal(updated.revision, 2);
assert.deepEqual(updated.routing, { roleRoutes: [implementation] });

const stale = yield* service
.update(
{
profileId: created.profileId,
name: "Routing policy",
instructions: "Stale instructions",
routing: { roleRoutes: [] },
expectedRevision: 1,
},
actor,
)
.pipe(Effect.flip);
assert.instanceOf(stale, DevelopmentProfileConflictError);
const afterStale = yield* service.read(created.profileId);
assert.equal(afterStale.instructions, "Use the routed model");
assert.deepEqual(afterStale.routing, { roleRoutes: [implementation] });

const instructionsOnly = yield* service.update(
{
profileId: created.profileId,
name: "Routing policy",
instructions: "Only instructions changed",
expectedRevision: 2,
},
actor,
);
assert.equal(instructionsOnly.revision, 3);
assert.deepEqual(instructionsOnly.routing, { roleRoutes: [implementation] });
}).pipe(Effect.provide(layerTest)),
);
54 changes: 37 additions & 17 deletions apps/server/src/developmentProfiles/DevelopmentProfileService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
ProjectDevelopmentProfileSetInput,
ProjectId,
ProjectRuntimeInstructions,
RuntimeProfileRoutingPolicy,
TrimmedNonEmptyString,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
Expand Down Expand Up @@ -83,6 +84,7 @@ interface ProfileRow {
readonly profile_id: string;
readonly name: string;
readonly instructions: string;
readonly routing_json: string | null;
readonly revision: number;
readonly created_at: string;
readonly updated_at: string;
Expand Down Expand Up @@ -115,16 +117,28 @@ const decodeAssignment = Schema.decodeUnknownEffect(ProjectDevelopmentProfile);
const decodeProject = Schema.decodeUnknownEffect(DevelopmentProfileProject);
const ProjectInstructionsJson = Schema.fromJsonString(ProjectRuntimeInstructions);
const decodeProjectInstructions = Schema.decodeUnknownEffect(ProjectInstructionsJson);
const ProfileRoutingJson = Schema.fromJsonString(RuntimeProfileRoutingPolicy);
const decodeProfileRouting = Schema.decodeUnknownEffect(ProfileRoutingJson);
const encodeProfileRouting = Schema.encodeEffect(ProfileRoutingJson);

const toProfile = (row: ProfileRow) => ({
profileId: DevelopmentProfileId.make(row.profile_id),
name: row.name,
instructions: row.instructions,
revision: row.revision,
createdAt: row.created_at,
updatedAt: row.updated_at,
createdBy: row.created_by,
updatedBy: row.updated_by,
const emptyProfileRouting = (): RuntimeProfileRoutingPolicy => ({ roleRoutes: [] });

const toProfile = Effect.fn("DevelopmentProfileService.toProfile")(function* (row: ProfileRow) {
const routing =
row.routing_json === null
? emptyProfileRouting()
: yield* decodeProfileRouting(row.routing_json);
return {
profileId: DevelopmentProfileId.make(row.profile_id),
name: row.name,
instructions: row.instructions,
routing,
revision: row.revision,
createdAt: row.created_at,
updatedAt: row.updated_at,
createdBy: row.created_by,
updatedBy: row.updated_by,
};
});

const toAssignment = (row: AssignmentRow) => ({
Expand Down Expand Up @@ -185,10 +199,10 @@ const make = Effect.gen(function* () {
profileId: DevelopmentProfileId,
) {
const rows = yield* sql<ProfileRow>`SELECT
profile_id, name, instructions, revision, created_at, updated_at, created_by, updated_by
profile_id, name, instructions, routing_json, revision, created_at, updated_at, created_by, updated_by
FROM development_profiles WHERE profile_id = ${profileId}`;
if (rows[0] === undefined) return yield* new DevelopmentProfileNotFoundError({ profileId });
return yield* decodeProfile(toProfile(rows[0]));
return yield* decodeProfile(yield* toProfile(rows[0]));
});

const findAssignment = Effect.fn("DevelopmentProfileService.findAssignment")(function* (
Expand Down Expand Up @@ -220,9 +234,11 @@ const make = Effect.gen(function* () {
)(
function* () {
const rows = yield* sql<ProfileRow>`SELECT
profile_id, name, instructions, revision, created_at, updated_at, created_by, updated_by
profile_id, name, instructions, routing_json, revision, created_at, updated_at, created_by, updated_by
FROM development_profiles ORDER BY created_at, profile_id`;
return yield* Effect.forEach(rows, (row) => decodeProfile(toProfile(row)));
return yield* Effect.forEach(rows, (row) =>
Effect.flatMap(toProfile(row), (profile) => decodeProfile(profile)),
);
},
sql.withTransaction,
sqlErrors,
Expand Down Expand Up @@ -250,15 +266,17 @@ const make = Effect.gen(function* () {
profileId: DevelopmentProfileId.make(yield* newId),
name: data.name,
instructions: data.instructions,
routing: data.routing ?? emptyProfileRouting(),
revision: 1,
createdAt: timestamp,
updatedAt: timestamp,
createdBy: actor,
updatedBy: actor,
});
const routingJson = yield* encodeProfileRouting(record.routing);
yield* sql`INSERT INTO development_profiles
(profile_id, name, instructions, revision, created_at, updated_at, created_by, updated_by)
VALUES (${record.profileId}, ${record.name}, ${record.instructions}, ${record.revision}, ${record.createdAt}, ${record.updatedAt}, ${record.createdBy}, ${record.updatedBy})`;
(profile_id, name, instructions, routing_json, revision, created_at, updated_at, created_by, updated_by)
VALUES (${record.profileId}, ${record.name}, ${record.instructions}, ${routingJson}, ${record.revision}, ${record.createdAt}, ${record.updatedAt}, ${record.createdBy}, ${record.updatedBy})`;
return record;
},
sql.withTransaction,
Expand All @@ -278,13 +296,15 @@ const make = Effect.gen(function* () {
...existing,
name: data.name,
instructions: data.instructions,
routing: data.routing ?? existing.routing,
revision: existing.revision + 1,
updatedAt,
updatedBy: actor,
});
const routingJson = yield* encodeProfileRouting(record.routing);
const changed = yield* sql`UPDATE development_profiles
SET name = ${record.name}, instructions = ${record.instructions}, revision = ${record.revision},
updated_at = ${record.updatedAt}, updated_by = ${record.updatedBy}
SET name = ${record.name}, instructions = ${record.instructions}, routing_json = ${routingJson},
revision = ${record.revision}, updated_at = ${record.updatedAt}, updated_by = ${record.updatedBy}
WHERE profile_id = ${record.profileId} AND revision = ${existing.revision}
RETURNING profile_id`;
if (changed.length !== 1) {
Expand Down
87 changes: 15 additions & 72 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
CommandId,
type RunId,
isProviderAvailable,
MessageId,
type ModelSelection,
NodeId,
Expand Down Expand Up @@ -56,7 +55,6 @@ import {
type ProviderInteractionMode,
type ProviderInstanceId,
type ProviderOptionDescriptor,
type ProviderOptionSelection,
ProviderRequestKind,
type RuntimeMode,
type ScheduledTask,
Expand Down Expand Up @@ -103,6 +101,11 @@ import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts";
import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import {
providerConstraintMessages,
providerEligibilityIssues,
providerOptionSelectionProblems,
} from "../provider/providerEligibility.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../serverSettings.ts";
import {
Expand Down Expand Up @@ -362,68 +365,6 @@ function capabilityModelOption(descriptor: ProviderOptionDescriptor): Orchestrat
};
}

function providerConstraints(
provider: ServerProvider | undefined,
supportsOrchestrationV2: boolean,
): ReadonlyArray<string> {
const constraints: Array<string> = [];
if (!supportsOrchestrationV2) {
constraints.push("No V2 provider adapter is registered.");
}
if (provider === undefined) return constraints;
if (!isProviderAvailable(provider)) {
constraints.push(provider.unavailableReason ?? "Provider driver is unavailable.");
}
if (!provider.enabled) {
constraints.push("Provider instance is disabled.");
// Disabled snapshots contain placeholders for installation, health, and auth.
return constraints;
}
if (!provider.installed) constraints.push("Provider executable is not installed.");
if (provider.status === "error" || provider.status === "disabled") {
constraints.push(provider.message ?? `Provider status is ${provider.status}.`);
}
if (provider.auth.status === "unauthenticated") {
constraints.push("Provider is not authenticated.");
}
return constraints;
}

/** Skip checks without descriptors; reject duplicate IDs because consumers disagree on precedence. */
function invalidOptionSelections(
selections: ReadonlyArray<ProviderOptionSelection>,
descriptors: ReadonlyArray<ProviderOptionDescriptor> | undefined,
): ReadonlyArray<string> {
const problems: Array<string> = [];
const seen = new Set<string>();
for (const selection of selections) {
if (seen.has(selection.id)) {
problems.push(`Option ${selection.id} was specified more than once.`);
continue;
}
seen.add(selection.id);
if (descriptors === undefined) continue;
const descriptor = descriptors.find((candidate) => candidate.id === selection.id);
if (descriptor === undefined) {
const known = descriptors.map((candidate) => candidate.id).join(", ");
problems.push(`Unknown option ${selection.id}; supported options: ${known || "none"}.`);
continue;
}
if (descriptor.type === "boolean" && typeof selection.value !== "boolean") {
problems.push(`Option ${selection.id} expects a boolean value.`);
continue;
}
if (
descriptor.type === "select" &&
!descriptor.options.some((choice) => choice.id === selection.value)
) {
const choices = descriptor.options.map((choice) => choice.id).join(", ");
problems.push(`Option ${selection.id} must be one of: ${choices}.`);
}
}
return problems;
}

function taskStatusForRun(
run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork"> | undefined,
): OrchestratorMcpDelegateTaskResult["status"] {
Expand Down Expand Up @@ -1352,7 +1293,8 @@ const make = Effect.gen(function* () {
);
}
const healthyCandidates = candidates.filter(
(candidate) => providerConstraints(candidate, true).length === 0,
(candidate) =>
providerConstraintMessages(providerEligibilityIssues(candidate, true)).length === 0,
);
const inheritedCandidate = healthyCandidates.find(
(candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,
Expand Down Expand Up @@ -1397,9 +1339,8 @@ const make = Effect.gen(function* () {
`Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,
);
}
const constraints = providerConstraints(
provider,
orchestrationCapableInstanceIds.has(provider.instanceId),
const constraints = providerConstraintMessages(
providerEligibilityIssues(provider, orchestrationCapableInstanceIds.has(provider.instanceId)),
);
if (constraints.length > 0) {
return yield* failure(
Expand Down Expand Up @@ -1437,7 +1378,7 @@ const make = Effect.gen(function* () {
if (requestedOptions !== undefined) {
const descriptors = provider.models.find((candidate) => candidate.slug === model)
?.capabilities?.optionDescriptors;
const invalid = invalidOptionSelections(requestedOptions, descriptors);
const invalid = providerOptionSelectionProblems(requestedOptions, descriptors);
if (invalid.length > 0) {
return yield* failure(
"invalid_request",
Expand Down Expand Up @@ -2081,9 +2022,11 @@ const make = Effect.gen(function* () {
runtimeMode: limits.runtimeMode,
interactionMode: limits.interactionMode,
providers: providers.map((provider) => {
const constraints = providerConstraints(
provider,
orchestrationCapableInstanceIds.has(provider.instanceId),
const constraints = providerConstraintMessages(
providerEligibilityIssues(
provider,
orchestrationCapableInstanceIds.has(provider.instanceId),
),
);
const { listed, omitted } = listCapabilityModels({
provider,
Expand Down
Loading
Loading