Skip to content

Commit c97525c

Browse files
committed
feat(server): persist overrides for built-in agent guidance
1 parent da1eab0 commit c97525c

23 files changed

Lines changed: 385 additions & 74 deletions

File tree

‎apps/server/src/mcp/toolkits/environment/handlers.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export function preferences(settings: ServerSettings) {
1818
} = settings;
1919
const characters = Array.from(sourceControlWritingStyle.customInstructions);
2020
return {
21+
agentInstructionOverrides: settings.agentInstructionOverrides,
2122
defaultThreadEnvMode,
2223
newWorktreesStartFromOrigin,
2324
enableProviderUpdateChecks,

‎apps/server/src/mcp/toolkits/environment/tools.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as Settings from "../../../serverSettings.ts";
1616
import * as McpInvocationContext from "../../McpInvocationContext.ts";
1717

1818
const PreferenceFields = {
19+
agentInstructionOverrides: ServerSettings.fields.agentInstructionOverrides,
1920
defaultThreadEnvMode: ServerSettings.fields.defaultThreadEnvMode,
2021
newWorktreesStartFromOrigin: ServerSettings.fields.newWorktreesStartFromOrigin,
2122
enableProviderUpdateChecks: ServerSettings.fields.enableProviderUpdateChecks,
@@ -59,6 +60,7 @@ const EnvironmentPreferencesTool = Tool.make("t3_environment_preferences_update"
5960
"Update environment-wide preferences. Live full-access or default caller thread only. Omitted fields are unchanged; `customInstructions: ''` clears it.",
6061
parameters: Schema.Struct({
6162
environmentId: OrchestratorMcpEnvironmentTarget,
63+
agentInstructionOverrides: ServerSettingsPatch.fields.agentInstructionOverrides,
6264
defaultThreadEnvMode: ServerSettingsPatch.fields.defaultThreadEnvMode,
6365
newWorktreesStartFromOrigin: ServerSettingsPatch.fields.newWorktreesStartFromOrigin,
6466
enableProviderUpdateChecks: ServerSettingsPatch.fields.enableProviderUpdateChecks,

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

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,11 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
625625
});
626626

627627
describe("ClaudeAdapterV2 device instructions", () => {
628-
const options = (input: { readonly mcp: boolean; readonly deviceToolsAvailable: boolean }) =>
628+
const options = (input: {
629+
readonly mcp: boolean;
630+
readonly deviceToolsAvailable: boolean;
631+
readonly deviceInstructions?: string;
632+
}) =>
629633
ClaudeAdapterV2.makeClaudeQueryOptions({
630634
modelSelection: {
631635
instanceId: ProviderInstanceId.make("claudeAgent"),
@@ -638,6 +642,9 @@ describe("ClaudeAdapterV2 device instructions", () => {
638642
? { mcpServers: { "t3-code": { type: "http" as const, url: "http://127.0.0.1/mcp" } } }
639643
: {}),
640644
deviceToolsAvailable: input.deviceToolsAvailable,
645+
...(input.deviceInstructions === undefined
646+
? {}
647+
: { instructionOverrides: { devices: input.deviceInstructions } }),
641648
environment: {},
642649
});
643650
const append = (input: { readonly mcp: boolean; readonly deviceToolsAvailable: boolean }) =>
@@ -656,10 +663,7 @@ describe("ClaudeAdapterV2 device instructions", () => {
656663

657664
it("gives native subagents the device block only in a session with device access", async () => {
658665
// Subagents start from their task prompt, not the parent's system prompt.
659-
const subagentContext = (input: {
660-
readonly mcp: boolean;
661-
readonly deviceToolsAvailable: boolean;
662-
}) =>
666+
const subagentContext = (input: Parameters<typeof options>[0]) =>
663667
Promise.all(
664668
(options(input).hooks?.SubagentStart ?? []).flatMap((matcher) =>
665669
matcher.hooks.map((hook) =>
@@ -686,6 +690,23 @@ describe("ClaudeAdapterV2 device instructions", () => {
686690
},
687691
},
688692
]);
693+
const deviceInstructions = "Use the configured device workflow.";
694+
const overridden = options({ mcp: true, deviceToolsAvailable: true, deviceInstructions });
695+
assert.include(
696+
(overridden.systemPrompt as { readonly append: string }).append,
697+
deviceInstructions,
698+
);
699+
assert.deepEqual(
700+
await subagentContext({ mcp: true, deviceToolsAvailable: true, deviceInstructions }),
701+
[
702+
{
703+
hookSpecificOutput: {
704+
hookEventName: "SubagentStart",
705+
additionalContext: deviceInstructions,
706+
},
707+
},
708+
],
709+
);
689710
assert.deepEqual(await subagentContext({ mcp: true, deviceToolsAvailable: false }), []);
690711
assert.deepEqual(await subagentContext({ mcp: false, deviceToolsAvailable: true }), []);
691712
});

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

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { AgentInstructionOverrides } from "@t3tools/contracts";
12
import * as DocumentText from "../../provider/DocumentText.ts";
23
import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
34
import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";
@@ -170,10 +171,7 @@ import {
170171
} from "../../provider/claudeUsageLimits.ts";
171172
import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
172173
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
173-
import {
174-
T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
175-
T3_CODE_ORCHESTRATION_INSTRUCTIONS,
176-
} from "@t3tools/provider-core/server/orchestrationInstructions";
174+
import { resolveAgentInstructions } from "@t3tools/provider-core/server/orchestrationInstructions";
177175
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
178176
import {
179177
mcpToolPresentation,
@@ -1438,13 +1436,15 @@ To wait for a background command or Monitor you started (tests, a build), call \
14381436
`;
14391437

14401438
// Native subagents start from their task, not this session's system prompt.
1441-
const subagentDeviceInstructions: HookCallback = () =>
1442-
Promise.resolve({
1443-
hookSpecificOutput: {
1444-
hookEventName: "SubagentStart",
1445-
additionalContext: T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
1446-
},
1447-
});
1439+
const subagentDeviceInstructions =
1440+
(instructions: string): HookCallback =>
1441+
() =>
1442+
Promise.resolve({
1443+
hookSpecificOutput: {
1444+
hookEventName: "SubagentStart",
1445+
additionalContext: instructions,
1446+
},
1447+
});
14481448

14491449
export function makeClaudeQueryOptions(input: {
14501450
readonly modelSelection: ModelSelection;
@@ -1459,6 +1459,7 @@ export function makeClaudeQueryOptions(input: {
14591459
readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
14601460
/** The thread's T3 MCP session holds the `device` capability. */
14611461
readonly deviceToolsAvailable?: boolean;
1462+
readonly instructionOverrides?: AgentInstructionOverrides | null;
14621463
readonly tools?: ClaudeAgentSdkQueryTools;
14631464
readonly allowedTools?: ReadonlyArray<string>;
14641465
readonly disallowedTools?: ReadonlyArray<string>;
@@ -1523,6 +1524,7 @@ export function makeClaudeQueryOptions(input: {
15231524
...compactQuerySettings,
15241525
env: { ...compactQuerySettings?.env, ENABLE_TOOL_SEARCH: input.toolSearchOverride },
15251526
} as ClaudeSdkSettings);
1527+
const resolvedInstructions = resolveAgentInstructions(input.instructionOverrides);
15261528
const deviceInstructions = input.mcpServers !== undefined && input.deviceToolsAvailable === true;
15271529
const options: ClaudeAgentSdkQueryOptions = {
15281530
model: compiledSelection.apiModelId,
@@ -1576,16 +1578,20 @@ export function makeClaudeQueryOptions(input: {
15761578
buildRuntimeInstructions({ harness: "Claude Code" }) +
15771579
(input.mcpServers === undefined
15781580
? ""
1579-
: T3_CODE_ORCHESTRATION_INSTRUCTIONS +
1581+
: resolvedInstructions.orchestration +
15801582
CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS +
1581-
(deviceInstructions
1582-
? `\n${T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH}\n`
1583-
: "")),
1583+
(deviceInstructions ? `\n${resolvedInstructions.devicesWithToolSearch}\n` : "")),
15841584
...launchAppendSystemPrompt,
15851585
].join("\n\n"),
15861586
},
15871587
...(deviceInstructions
1588-
? { hooks: { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] } }
1588+
? {
1589+
hooks: {
1590+
SubagentStart: [
1591+
{ hooks: [subagentDeviceInstructions(resolvedInstructions.devicesWithToolSearch)] },
1592+
],
1593+
},
1594+
}
15891595
: {}),
15901596
...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),
15911597
};
@@ -4542,6 +4548,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
45424548
}),
45434549
openSession: Effect.fn("ClaudeAdapterV2.openSession")(
45444550
function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
4551+
const instructionOverrides = Option.isSome(serverSettings)
4552+
? (yield* serverSettings.value.getSettings).agentInstructionOverrides
4553+
: null;
45454554
const sessionScope = yield* Effect.scope;
45464555
const now = yield* DateTime.now;
45474556
const session = providerSession({
@@ -9910,6 +9919,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
99109919
launchArgSettings,
99119920
);
99129921
const queryOptions = makeClaudeQueryOptions({
9922+
instructionOverrides,
99139923
modelSelection: turnInput.modelSelection,
99149924
nativeThreadId,
99159925
resume: shouldResume,

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { AgentInstructionOverrides } from "@t3tools/contracts";
2+
import * as ServerSettings from "../../serverSettings.ts";
13
import { pipe } from "effect/Function";
24
import * as DocumentText from "../../provider/DocumentText.ts";
35
import { revertCodexThread } from "../../provider/CodexThreadRevert.ts";
@@ -728,6 +730,7 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur
728730
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
729731
readonly modelSelection: ModelSelection;
730732
readonly hasT3Mcp?: boolean;
733+
readonly instructionOverrides?: AgentInstructionOverrides | null;
731734
readonly browserToolsAvailable?: boolean;
732735
readonly deviceToolsAvailable?: boolean;
733736
/** ChatGPT token sharing does not accept service tiers. */
@@ -767,6 +770,7 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur
767770
browser: input.browserToolsAvailable ?? true,
768771
device: input.deviceToolsAvailable ?? false,
769772
},
773+
input.instructionOverrides,
770774
)
771775
: undefined;
772776
const additionalContext =
@@ -1615,6 +1619,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
16151619
adapterOptions: CodexAdapterV2Options,
16161620
) {
16171621
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
1622+
const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
16181623
const readMcpSession = (threadId: ThreadId | null) =>
16191624
// @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
16201625
threadId === null ? Effect.succeed(undefined) : mcpSessions.read(threadId);
@@ -1632,6 +1637,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
16321637
}),
16331638
openSession: Effect.fn("CodexAdapterV2.openSession")(
16341639
function* (input) {
1640+
const instructionOverrides = Option.isSome(serverSettings)
1641+
? (yield* serverSettings.value.getSettings).agentInstructionOverrides
1642+
: null;
16351643
const scope = yield* Scope.Scope;
16361644
const resolvedRuntime =
16371645
adapterOptions.resolveRuntime === undefined
@@ -6486,6 +6494,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
64866494
runtimePolicy: turnInput.runtimePolicy,
64876495
modelSelection: turnInput.modelSelection,
64886496
hasT3Mcp: mcpSession !== undefined,
6497+
instructionOverrides,
64896498
browserToolsAvailable: mcpSession?.browserToolsAvailable ?? true,
64906499
deviceToolsAvailable: mcpSession?.capabilities?.has("device") ?? false,
64916500
omitServiceTier: adapterOptions.resolveRuntime !== undefined,

‎apps/server/src/provider/CodexDeveloperInstructions.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,31 @@ describe("Codex device context", () => {
9292
function runtimeInstructions(runtime: Parameters<typeof buildCodexAdditionalContext>[0]) {
9393
return buildCodexAdditionalContext(runtime).t3_code_runtime!.value;
9494
}
95+
96+
describe("Codex instruction overrides", () => {
97+
it("keeps long Unicode replacements complete without exceeding per-entry limits", () => {
98+
const replacement = "Custom policy 🙂\n".repeat(1000);
99+
const context = buildCodexAdditionalContext(
100+
{ model: "custom" },
101+
{ browser: true, device: true },
102+
{ orchestration: "", visuals: replacement, browser: "", devices: replacement },
103+
);
104+
const collect = (prefix: string) =>
105+
Object.entries(context)
106+
.filter(([key]) => key.startsWith(prefix))
107+
.map(([, entry]) => entry.value)
108+
.join("");
109+
NodeAssert.equal(collect("t3_code_orchestration_"), replacement);
110+
NodeAssert.equal(collect("t3_code_tools"), replacement);
111+
for (const entry of Object.values(context)) {
112+
NodeAssert.ok(
113+
Buffer.byteLength(entry.value, "utf8") <= CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES,
114+
);
115+
}
116+
const unavailable = buildCodexAdditionalContext({ model: "custom" }, false, {
117+
devices: replacement,
118+
browser: replacement,
119+
});
120+
NodeAssert.ok(!Object.keys(unavailable).some((key) => key.startsWith("t3_code_tools")));
121+
});
122+
});
Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1+
import type { AgentInstructionOverrides } from "@t3tools/contracts";
12
import type { V2TurnStartParams__AdditionalContextEntry } from "effect-codex-app-server/schema";
23
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
34

4-
import {
5-
T3_CODE_BROWSER_TOOL_INSTRUCTIONS,
6-
T3_CODE_DEVICE_TOOL_INSTRUCTIONS,
7-
T3_CODE_ORCHESTRATION_SECTIONS,
8-
} from "@t3tools/provider-core/server/orchestrationInstructions";
5+
import { resolveAgentInstructions } from "@t3tools/provider-core/server/orchestrationInstructions";
96

107
/** Codex silently truncates additionalContext values over 1,000 tokens, counted as UTF-8 bytes / 4. */
118
export const CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES = 4_000;
@@ -21,12 +18,13 @@ const normalizeAvailability = (
2118
typeof availability === "boolean" ? { browser: availability, device: false } : availability;
2219

2320
/** Instructions for unavailable tools would steer the model away from its remaining automation. */
24-
const toolInstructions = (availability: boolean | T3CodeToolAvailability): string => {
21+
const toolInstructions = (
22+
availability: boolean | T3CodeToolAvailability,
23+
overrides?: AgentInstructionOverrides | null,
24+
): string => {
25+
const resolved = resolveAgentInstructions(overrides);
2526
const tools = normalizeAvailability(availability);
26-
return [
27-
tools.browser ? T3_CODE_BROWSER_TOOL_INSTRUCTIONS : "",
28-
tools.device ? T3_CODE_DEVICE_TOOL_INSTRUCTIONS : "",
29-
]
27+
return [tools.browser ? resolved.browser : "", tools.device ? resolved.devices : ""]
3028
.filter(Boolean)
3129
.join("\n\n");
3230
};
@@ -41,20 +39,48 @@ export interface CodexRuntimeInfo {
4139
export function buildCodexAdditionalContext(
4240
runtime: CodexRuntimeInfo,
4341
toolsAvailable: boolean | T3CodeToolAvailability = true,
42+
overrides?: AgentInstructionOverrides | null,
4443
): Record<string, V2TurnStartParams__AdditionalContextEntry> {
45-
const tools = toolInstructions(toolsAvailable);
44+
const tools = toolInstructions(toolsAvailable, overrides);
4645
// Split values to fit per-entry caps; number keys because Codex emits them in key order.
4746
return {
4847
...Object.fromEntries(
49-
T3_CODE_ORCHESTRATION_SECTIONS.map((section, index) => [
50-
`t3_code_orchestration_${String(index + 1).padStart(2, "0")}`,
51-
{ kind: "application" as const, value: section },
52-
]),
48+
resolveAgentInstructions(overrides)
49+
.orchestrationSections.flatMap(splitContextValue)
50+
.map((section, index, sections) => [
51+
`t3_code_orchestration_${String(index + 1).padStart(Math.max(2, String(sections.length).length), "0")}`,
52+
{ kind: "application" as const, value: section },
53+
]),
5354
),
5455
t3_code_runtime: {
5556
kind: "application",
5657
value: buildRuntimeInstructions({ harness: "Codex", ...runtime }),
5758
},
58-
...(tools ? { t3_code_tools: { kind: "application", value: tools } } : {}),
59+
...Object.fromEntries(
60+
splitContextValue(tools).map((value, index, sections) => [
61+
index === 0
62+
? "t3_code_tools"
63+
: `t3_code_tools_${String(index + 1).padStart(Math.max(2, String(sections.length).length), "0")}`,
64+
{ kind: "application" as const, value },
65+
]),
66+
),
5967
};
6068
}
69+
70+
function splitContextValue(value: string): ReadonlyArray<string> {
71+
const chunks: string[] = [];
72+
let chunk = "";
73+
let bytes = 0;
74+
for (const character of value) {
75+
const size = Buffer.byteLength(character, "utf8");
76+
if (bytes + size > CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES) {
77+
chunks.push(chunk);
78+
chunk = "";
79+
bytes = 0;
80+
}
81+
chunk += character;
82+
bytes += size;
83+
}
84+
if (chunk.length > 0) chunks.push(chunk);
85+
return chunks;
86+
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"claudeSystemAppendBytes": 5135,
33
"codexAdditionalContextBytes": 6865,
4-
"mcpToolListJsonBytes": 45907
4+
"mcpToolListJsonBytes": 46086
55
}

‎apps/server/src/serverSettings.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,31 @@ const recordProviderUsage = (provider: string, instanceId: string | null = provi
9494
});
9595

9696
it.layer(NodeServices.layer)("server settings", (it) => {
97+
it.effect("persists instruction replacements and omissions and can restore defaults", () =>
98+
Effect.gen(function* () {
99+
const service = yield* ServerSettingsModule.ServerSettingsService;
100+
const fs = yield* FileSystem.FileSystem;
101+
const config = yield* ServerConfig.ServerConfig;
102+
yield* service.updateSettings({
103+
agentInstructionOverrides: { visuals: "Return an artifact link.", browser: "" },
104+
});
105+
const saved = yield* fs
106+
.readFileString(config.settingsPath)
107+
.pipe(Effect.flatMap(decodeServerSettingsJson));
108+
assert.deepEqual(saved.agentInstructionOverrides, {
109+
visuals: "Return an artifact link.",
110+
browser: "",
111+
});
112+
const next = yield* service.updateSettings({ agentInstructionOverrides: { visuals: null } });
113+
assert.deepEqual(next.agentInstructionOverrides, { visuals: null, browser: "" });
114+
yield* service.updateSettings({ agentInstructionOverrides: null });
115+
const restored = yield* fs
116+
.readFileString(config.settingsPath)
117+
.pipe(Effect.flatMap(decodeServerSettingsJson));
118+
assert.isNull(restored.agentInstructionOverrides);
119+
}).pipe(Effect.provide(layerServerSettings())),
120+
);
121+
97122
it.effect("serializes concurrent model preference edits without cancelling duplicate adds", () =>
98123
Effect.gen(function* () {
99124
const service = yield* ServerSettingsModule.ServerSettingsService;

0 commit comments

Comments
 (0)