Skip to content

Commit 99a3182

Browse files
committed
fix(server): preserve codex session skill policies across recovery
1 parent 18622db commit 99a3182

9 files changed

Lines changed: 125 additions & 76 deletions

‎apps/server/src/mcp/OrchestratorMcpService.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2712,7 +2712,17 @@ describe("OrchestratorMcpService provider resolution", () => {
27122712
getThreadRecords: (threadId) =>
27132713
Effect.succeed(
27142714
threadId === parentThreadId
2715-
? parentProjection(commands.length > 0 ? [task] : [], inherited)
2715+
? {
2716+
...parentProjection(commands.length > 0 ? [task] : [], inherited),
2717+
thread: {
2718+
...parentProjection([], inherited).thread,
2719+
modelSelection: {
2720+
instanceId: inherited.instanceId,
2721+
model: inherited.model,
2722+
options: inherited.options,
2723+
},
2724+
},
2725+
}
27162726
: childProjection,
27172727
),
27182728
dispatch: (command) =>

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2230,7 +2230,11 @@ const make = Effect.gen(function* () {
22302230
const settings = yield* serverSettings.getSettings.pipe(
22312231
Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),
22322232
);
2233-
const inherited = parent?.thread.modelSelection;
2233+
const inherited =
2234+
parent === undefined
2235+
? undefined
2236+
: (ThreadManagementService.latestActiveRun(parent)?.modelSelection ??
2237+
parent.thread.modelSelection);
22342238
const searchTerms = input.search?.toLowerCase().split(/\s+/).filter(Boolean) ?? [];
22352239
return {
22362240
parentThreadId: parent?.thread.id ?? null,
@@ -2346,7 +2350,10 @@ const make = Effect.gen(function* () {
23462350
});
23472351
const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId);
23482352
const target = yield* resolveTargetRechecking({
2349-
parent,
2353+
parent: {
2354+
...parent,
2355+
thread: { ...parent.thread, modelSelection: parentRun.modelSelection },
2356+
},
23502357
target: input.target,
23512358
providers,
23522359
skipProjectEnablementFilter: isRetryOfAcceptedDelegation,
@@ -2755,7 +2762,10 @@ const make = Effect.gen(function* () {
27552762
.pipe(Effect.mapError(threadManagementFailure))
27562763
: null;
27572764
const target = yield* resolveTargetRechecking({
2758-
parent,
2765+
parent: {
2766+
...parent,
2767+
thread: { ...parent.thread, modelSelection: parentRun.modelSelection },
2768+
},
27592769
target:
27602770
committedThread === null
27612771
? request.target

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,17 +1191,7 @@ describe("CodexAdapterV2 session initialize", () => {
11911191
const session = yield* openReplaySession(
11921192
makeCodexReplayTranscript({
11931193
scenario: "initialize-interrupted",
1194-
entries: [
1195-
...preamble.slice(0, 2),
1196-
...preamble.slice(0, 1).map((entry) => withReplayRequestId(entry, 2)),
1197-
{
1198-
type: "emit_inbound",
1199-
label: "initialize-rejected",
1200-
frame: { id: 2, error: { code: -32600, message: "Already initialized" } },
1201-
},
1202-
...preamble.slice(2, 3),
1203-
...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)),
1204-
],
1194+
entries: [...preamble],
12051195
}),
12061196
(entry) =>
12071197
entry.label === "initialize"
@@ -1220,7 +1210,7 @@ describe("CodexAdapterV2 session initialize", () => {
12201210

12211211
const providerThread = yield* session.ensureThread("thread-initialize-interrupted");
12221212
assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-interrupted");
1223-
assert.equal(session.initializeRequests(), 2);
1213+
assert.equal(session.initializeRequests(), 1);
12241214
}).pipe(
12251215
Effect.scoped,
12261216
Effect.provide(

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts‎

Lines changed: 36 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1723,50 +1723,40 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
17231723
}),
17241724
),
17251725
);
1726-
const initialized = yield* Ref.make(false);
1727-
// Codex rejects a second initialize on the shared app-server.
1728-
const initializePermit = yield* Semaphore.make(1);
17291726
const initializedUserAgent = yield* Ref.make("");
1730-
const ensureInitialized = initializePermit.withPermit(
1731-
Effect.gen(function* () {
1732-
const alreadyInitialized = yield* Ref.get(initialized);
1733-
if (alreadyInitialized) {
1734-
return;
1735-
}
1736-
1737-
const userAgent = yield* client
1738-
.request("initialize", {
1739-
clientInfo: buildCodexInitializeParams().clientInfo,
1740-
capabilities: CODEX_CLIENT_CAPABILITIES,
1741-
})
1742-
.pipe(
1743-
Effect.map((response) => response.userAgent),
1744-
Effect.catchTags({
1745-
// Interruption can leave Codex initialized before the local flag is set.
1746-
CodexAppServerRequestError: (error) =>
1747-
error.code === -32600 && error.errorMessage === "Already initialized"
1748-
? Effect.succeed(null)
1749-
: Effect.fail(error),
1750-
}),
1751-
);
1752-
if (userAgent !== null) yield* Ref.set(initializedUserAgent, userAgent);
1753-
const version = userAgent && /\/(\S+)/u.exec(userAgent)?.[1];
1754-
const advisory =
1755-
version && adapterOptions.compatibility
1756-
? yield* adapterOptions.compatibility(version)
1757-
: undefined;
1758-
if (advisory?.status === "broken") {
1759-
const target =
1760-
advisory.recommendedVersion ?? advisory.recommendedRange ?? "a newer version";
1761-
return yield* new ProviderSetupError({
1762-
instanceId: adapterOptions.instanceId,
1763-
operation: "runtime",
1764-
detail: `Codex ${version} does not work with this T3 Code release. Update Codex to ${target}, then retry.`,
1765-
});
1766-
}
1767-
yield* client.notify("initialized", undefined);
1768-
yield* Ref.set(initialized, true);
1769-
}),
1727+
// Keep the handshake in the session scope when its first caller is interrupted.
1728+
const [initializeFiber, invalidateInitialize] = yield* Effect.cachedInvalidateWithTTL(
1729+
Effect.forkIn(
1730+
Effect.gen(function* () {
1731+
const userAgent = yield* client
1732+
.request("initialize", {
1733+
clientInfo: buildCodexInitializeParams().clientInfo,
1734+
capabilities: CODEX_CLIENT_CAPABILITIES,
1735+
})
1736+
.pipe(Effect.map((response) => response.userAgent));
1737+
yield* Ref.set(initializedUserAgent, userAgent);
1738+
const version = userAgent && /\/(\S+)/u.exec(userAgent)?.[1];
1739+
const advisory =
1740+
version && adapterOptions.compatibility
1741+
? yield* adapterOptions.compatibility(version)
1742+
: undefined;
1743+
if (advisory?.status === "broken") {
1744+
const target =
1745+
advisory.recommendedVersion ?? advisory.recommendedRange ?? "a newer version";
1746+
return yield* new ProviderSetupError({
1747+
instanceId: adapterOptions.instanceId,
1748+
operation: "runtime",
1749+
detail: `Codex ${version} does not work with this T3 Code release. Update Codex to ${target}, then retry.`,
1750+
});
1751+
}
1752+
yield* client.notify("initialized", undefined);
1753+
}),
1754+
scope,
1755+
),
1756+
Infinity,
1757+
);
1758+
const ensureInitialized = Effect.flatMap(initializeFiber, Fiber.join).pipe(
1759+
Effect.tapError(() => invalidateInitialize),
17701760
);
17711761
const resolveThreadSkills = Effect.fn("CodexAdapterV2.resolveThreadSkills")(function* (
17721762
selection: Pick<ModelSelection, "skillOverrides"> | undefined,
@@ -7855,12 +7845,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
78557845
}
78567846
// thread/revert requires the thread loaded in this app-server; resume after restart or idle release.
78577847
if (!loaded) {
7858-
yield* assertCodexSkillOverridesUnchanged(
7859-
input.modelSelection.skillOverrides,
7860-
threadInput.providerThread.nativeMetadata?.skillConfiguration?.overrides,
7861-
);
7848+
const configured =
7849+
threadInput.providerThread.nativeMetadata?.skillConfiguration?.overrides;
78627850
const skillConfiguration = yield* resolveThreadSkills(
7863-
input.modelSelection,
7851+
configured === undefined ? undefined : { skillOverrides: configured },
78647852
input.runtimePolicy.cwd,
78657853
);
78667854
yield* client.raw.request("thread/resume", {

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -777,9 +777,14 @@ function queuedRunModelSelection(
777777
run: OrchestrationV2Run,
778778
): ModelSelection {
779779
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
780-
return followsCurrentConversation(message)
780+
const selection = followsCurrentConversation(message)
781781
? projection.thread.modelSelection
782782
: run.modelSelection;
783+
return selection.skillOverrides === undefined &&
784+
selection.instanceId === run.modelSelection.instanceId &&
785+
run.modelSelection.skillOverrides !== undefined
786+
? { ...selection, skillOverrides: run.modelSelection.skillOverrides }
787+
: selection;
783788
}
784789

785790
function usageLimitHoldsQueue(
@@ -5479,7 +5484,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
54795484
]);
54805485
projection = yield* getProjectionWithPendingEvents(command.threadId, events);
54815486
}
5482-
const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
5487+
const requestedSelection = command.modelSelection ?? projection.thread.modelSelection;
5488+
const storedSkillOverrides = projection.providerThreads.find(
5489+
(thread) =>
5490+
thread.id === projection.thread.activeProviderThreadId &&
5491+
thread.driver === "codex" &&
5492+
thread.providerInstanceId === requestedSelection.instanceId,
5493+
)?.nativeMetadata?.skillConfiguration?.overrides;
5494+
const modelSelection =
5495+
requestedSelection.skillOverrides === undefined && storedSkillOverrides !== undefined
5496+
? { ...requestedSelection, skillOverrides: storedSkillOverrides }
5497+
: requestedSelection;
54835498
let dispatchMode = resolveMessageDispatchIntent(
54845499
projection,
54855500
command.dispatchMode,

‎apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -988,23 +988,44 @@ function makeLocalCommandHarness(input: {
988988
}
989989

990990
effectIt.effect.each([
991-
["claudeAgent", "Session skill overrides unavailable"],
992-
["codex", "Session skill overrides require a fresh thread"],
991+
["claudeAgent", "Session skill overrides unavailable", undefined, []],
992+
["codex", "Session skill overrides require a fresh thread", undefined, []],
993+
[
994+
"codex",
995+
"Session skill overrides cannot change",
996+
[{ path: "/skills/review/SKILL.md", enabled: false }],
997+
[],
998+
],
999+
["codex", "Session skill overrides cannot change", [], undefined],
9931000
] as const)(
9941001
"fails before opening %s with unsupported or contaminated skill overrides",
995-
([driver, title]) =>
1002+
([driver, title, configured, requested]) =>
9961003
Effect.gen(function* () {
9971004
const harness = makeLocalCommandHarness({ text: "Continue" });
9981005
const projection = harness.projection();
9991006
harness.setProjection({
10001007
...projection,
10011008
runs: projection.runs.map((run) => ({
10021009
...run,
1003-
modelSelection: { ...run.modelSelection, skillOverrides: [] },
1010+
modelSelection:
1011+
requested === undefined
1012+
? run.modelSelection
1013+
: { ...run.modelSelection, skillOverrides: requested },
10041014
})),
10051015
providerThreads: projection.providerThreads.map((thread) => ({
10061016
...thread,
10071017
driver: ProviderDriverKind.make(driver),
1018+
...(configured === undefined
1019+
? {}
1020+
: {
1021+
nativeMetadata: {
1022+
skillConfiguration: {
1023+
providerVersion: "0.165.0",
1024+
overrides: configured,
1025+
skills: [],
1026+
},
1027+
},
1028+
}),
10081029
})),
10091030
});
10101031
yield* harness.start;

‎apps/server/src/orchestration-v2/ProviderTurnStartService.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { modelSelectionsEqual } from "@t3tools/shared/model";
1+
import { CodexSkillOverrideError } from "../provider/CodexSkillOverrides.ts";
2+
import { modelSelectionsEqual, skillOverridesEqual } from "@t3tools/shared/model";
23
import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
34
import {
45
CommandId,
@@ -556,6 +557,20 @@ export const layer: Layer.Layer<
556557
});
557558
},
558559
);
560+
const configuredSkills = providerThread.nativeMetadata?.skillConfiguration;
561+
if (
562+
configuredSkills !== undefined &&
563+
!skillOverridesEqual(run.modelSelection.skillOverrides, configuredSkills.overrides)
564+
) {
565+
const error = new CodexSkillOverrideError({ reason: "session-policy-changed" });
566+
yield* settleStartFailure({
567+
signal: "skill-overrides-changed",
568+
title: "Session skill overrides cannot change",
569+
error,
570+
message: error.message,
571+
});
572+
return;
573+
}
559574
if (run.modelSelection.skillOverrides !== undefined && providerThread.driver !== "codex") {
560575
const error = new SessionSkillOverridesUnsupportedError();
561576
yield* settleStartFailure({
@@ -570,7 +585,7 @@ export const layer: Layer.Layer<
570585
run.modelSelection.skillOverrides !== undefined &&
571586
providerThread.nativeMetadata?.skillConfiguration === undefined &&
572587
(run.ordinal !== 1 ||
573-
Boolean(projection.thread.forkedFrom) ||
588+
projection.thread.forkedFrom?.type === "run" ||
574589
projection.contextHandoffs.length > 0)
575590
) {
576591
const error = new SessionSkillOverridesHistoryError();

‎apps/server/src/peer/RemoteDelegation.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,9 +213,9 @@ const make = Effect.gen(function* () {
213213
const parentNodeId = parentRun.rootNodeId;
214214
const { target } = input;
215215
if (
216-
parent.thread.modelSelection.skillOverrides !== undefined &&
216+
parentRun.modelSelection.skillOverrides !== undefined &&
217217
target.skillOverrides !== undefined &&
218-
!skillOverridesEqual(parent.thread.modelSelection.skillOverrides, target.skillOverrides)
218+
!skillOverridesEqual(parentRun.modelSelection.skillOverrides, target.skillOverrides)
219219
) {
220220
return yield* new OrchestratorMcpFailure({
221221
code: "invalid_request",
@@ -233,7 +233,7 @@ const make = Effect.gen(function* () {
233233
}
234234
// The provider and model inherit as they do for a task here. Another
235235
// provider there has no model to inherit, so the caller names one.
236-
const inherited = parent.thread.modelSelection;
236+
const inherited = parentRun.modelSelection;
237237
const instanceId = target.providerInstanceId ?? inherited.instanceId;
238238
const model =
239239
target.model ?? (instanceId === inherited.instanceId ? inherited.model : undefined);
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"claudeSystemAppendBytes": 5153,
33
"codexAdditionalContextBytes": 6883,
4-
"mcpToolListJsonBytes": 47020
4+
"mcpToolListJsonBytes": 47946
55
}

0 commit comments

Comments
 (0)