Skip to content

Commit fc0eb68

Browse files
committed
feat: append session instructions without replacing configured rules
Carry agentclientprotocol#585 (head 1a32623) onto alas: a client-neutral _meta.systemPrompt.append on session/new, load, resume and fork, advertised as InitializeResponse._meta.systemPrompt. The append is combined with the effective configured developer_instructions instead of replacing them, and does not require the AIR client declaration. On top of agentclientprotocol#585, a load or resume that repeats the append this adapter process already opened the thread with is accepted without a new override. Alas re-sends the same captured instructions when it reconnects to a live adapter, and agentclientprotocol#585 alone rejected every append on a loaded thread.
1 parent 961e62e commit fc0eb68

48 files changed

Lines changed: 441 additions & 41 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Use [OpenAI Codex](https://github.com/openai/codex) from [Agent Client Protocol]
2121
- Typed warnings and errors through the opt-in [AIR session failure extension](docs/air-extensions.md#session-failure).
2222
- All AIR extensions, capabilities, and `_meta` keys: [AIR extensions](docs/air-extensions.md).
2323
- A per-turn [agent file-change report](docs/air-extensions.md#agent-file-change-report) after capability negotiation.
24+
- Client-provided, session-scoped [system prompt append](docs/system-prompt-extension.md), preserving configured developer instructions.
2425
- Client-provided MCP servers over command-based stdio config and HTTP transport.
2526
- Slash commands: `/status`, `/mcp` (with `/mcp reconnect`), `/skills`, `/goal`, `/review`, `/review-branch`, `/review-commit`, `/compact`, and `/logout`, as well as configured skills.
2627

‎docs/air-extensions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ Only these differences are allowed:
5959
ACP defines no merge for `_meta` keys, so the `_meta` of each report keeps every key that the adapter sent before.
6060
- Bug fixes: a unique MCP startup tool call id, the result of a dynamic tool in `content`,
6161
no output after a tool call ended, and a terminal status for a replayed image generation.
62-
- Feature changes for every client: the `/mcp` command has a new description and an input hint.
62+
- Feature changes for every client: the `/mcp` command has a new description and an input hint; initialization advertises the opt-in [system prompt append extension](system-prompt-extension.md).
6363
- The client gets no AIR-only key.
6464
That is no `_meta.jetbrains.air` key and none of the earlier keys in [Removed keys](#removed-keys).
6565
- The output of a command arrives once, in the chunks or in `content`, as [Zed conventions](#zed-conventions) describe.

‎docs/system-prompt-extension.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Session system prompt append
2+
3+
Clients may send `_meta.systemPrompt.append` on `session/new`, `session/load`,
4+
`session/resume`, and `session/fork` to install session-scoped developer
5+
instructions. Ordinary prompts remain ordinary user messages. Codex owns tool
6+
execution, history, and compaction; this extension does not replace its base
7+
instructions or write instruction files.
8+
9+
Check the initialization response before using the extension:
10+
11+
```json
12+
{"_meta":{"systemPrompt":{"version":1,"append":true,"maxBytes":262144}}}
13+
```
14+
15+
Example session metadata:
16+
17+
```json
18+
{"_meta":{"systemPrompt":{"append":"Review database migrations for this session."}}}
19+
```
20+
21+
The adapter reads effective user/project `developer_instructions` for the
22+
requested working directory, honoring a `CODEX_CONFIG` override, and appends the
23+
client text with a blank line. The underlying configuration is not modified.
24+
Each session gets its own value; repeated loads reconstruct it from configuration
25+
rather than appending to the already-appended restored instructions.
26+
27+
Absent or whitespace-only text leaves the existing native lifecycle unchanged.
28+
With explicit text, new and forked threads receive the combined value; load and
29+
resume apply it to an **unloaded** thread. Codex ignores instruction overrides on
30+
already-loaded threads, including idle threads. Those requests are rejected
31+
rather than silently claiming success: close/unload the thread first, or open it
32+
in a fresh adapter process. A thread that this adapter process opened with the
33+
same append text is the exception: a client that reconnects to the live process
34+
and repeats the load or resume with unchanged text is accepted without a new
35+
override, because Codex already holds those instructions. Omitting metadata
36+
leaves native restoration and inheritance behavior to Codex. This is not an
37+
in-place instruction editor.
38+
39+
Only the `{ "append": "..." }` form is supported. Replacement strings, unknown
40+
fields, non-string values, and values over 256 KiB in UTF-8 are rejected before
41+
session creation or skill changes. Config lookup failures are propagated; the
42+
adapter never substitutes an empty configuration and loses user instructions.
43+
44+
AIR `customInstructions` remains supported on its upstream new-session path. Combining a nonblank `systemPrompt.append` with AIR `customInstructions` is rejected before thread creation rather than silently choosing an override.
45+
46+
The `clear: true` capability advertises explicit empty append support: `{append:""}` reloads only effective configured developer instructions, clearing a prior session addition. Omitted metadata remains unchanged. This requires an unloaded thread just like a nonempty append.

‎src/CodexAcpClient.ts‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {readSessionInstructionAppend} from "./SessionInstructions";
12
import {
23
type ApiKeyAuthRequest,
34
CODEX_API_KEY_ENV_VAR,
@@ -148,6 +149,13 @@ export class CodexAcpClient {
148149
private pendingLoginCompleted: Promise<AccountLoginCompletedNotification> | null = null;
149150
private pendingAccountUpdated: Promise<AccountUpdatedNotification> | null = null;
150151
private readonly sessionNotificationQueues = new Map<string, Promise<void>>();
152+
/**
153+
* The `systemPrompt.append` each thread was opened with in this process. A
154+
* client that reconnects to a live adapter sends `session/load` or
155+
* `session/resume` again with the same text; Codex already holds those
156+
* instructions, so a matching repeat is accepted without an override.
157+
*/
158+
private readonly appliedInstructionAppends = new Map<string, string>();
151159
private readonly subagents: CodexSubagentSubscriptions;
152160
private skillExtraRoots: string[] = [];
153161
private configPath: string | null = null;
@@ -672,17 +680,21 @@ export class CodexAcpClient {
672680
}
673681

674682
async resumeSession(request: acp.ResumeSessionRequest, onSubscribed?: () => void): Promise<SessionMetadata> {
683+
const append = readSessionInstructionAppend(request._meta);
684+
const instructionOverride = await this.sessionInstructionOverride(append, request.cwd, request.sessionId);
675685
const additionalDirectories = readAdditionalDirectories(request.cwd, request.additionalDirectories, request._meta);
676686
await this.refreshSkills(request.cwd, additionalDirectories);
677687

678688
const sessionConfig = await this.createSessionConfig(request.cwd, additionalDirectories, request.mcpServers ?? []);
679689
const response = await this.resumeThread({
680690
excludeTurns: true,
691+
...instructionOverride,
681692
config: sessionConfig.config,
682693
cwd: request.cwd,
683694
modelProvider: await this.getResumeModelProvider(),
684695
threadId: request.sessionId,
685696
});
697+
this.recordInstructionAppend(request.sessionId, append);
686698
onSubscribed?.();
687699
const codexModels = await this.fetchAvailableModels();
688700
const currentModelId = this.createModelId(codexModels, response.model, response.reasoningEffort).toString();
@@ -704,8 +716,9 @@ export class CodexAcpClient {
704716
releaseFailedFork: (threadId: string) => Promise<void> = threadId => this.closeSession(threadId),
705717
): Promise<SessionMetadata> {
706718
const additionalDirectories = readAdditionalDirectories(request.cwd, request.additionalDirectories, request._meta);
707-
return await runForkSession(request, additionalDirectories, {
719+
const metadata = await runForkSession(request, additionalDirectories, {
708720
codexClient: this.codexClient,
721+
sessionInstructionOverride: (append, cwd) => this.sessionInstructionOverride(append, cwd),
709722
refreshSkills: (cwd, directories) => this.refreshSkills(cwd, directories),
710723
createSessionConfig: (cwd, directories, mcpServers) =>
711724
this.createSessionConfig(cwd, directories, mcpServers),
@@ -716,20 +729,26 @@ export class CodexAcpClient {
716729
getCollaborationMode: sessionId => this.getCollaborationMode(sessionId),
717730
releaseFailedFork,
718731
});
732+
this.recordInstructionAppend(metadata.sessionId, readSessionInstructionAppend(request._meta));
733+
return metadata;
719734
}
720735

721736
async loadSession(request: acp.LoadSessionRequest, onSubscribed?: () => void): Promise<SessionMetadataWithThread> {
737+
const append = readSessionInstructionAppend(request._meta);
738+
const instructionOverride = await this.sessionInstructionOverride(append, request.cwd, request.sessionId);
722739
const additionalDirectories = readAdditionalDirectories(request.cwd, request.additionalDirectories, request._meta);
723740
await this.refreshSkills(request.cwd, additionalDirectories);
724741

725742
const sessionConfig = await this.createSessionConfig(request.cwd, additionalDirectories, request.mcpServers ?? []);
726743
const response = await this.resumeThread({
727744
excludeTurns: true,
745+
...instructionOverride,
728746
config: sessionConfig.config,
729747
cwd: request.cwd,
730748
modelProvider: await this.getResumeModelProvider(),
731749
threadId: request.sessionId,
732750
});
751+
this.recordInstructionAppend(request.sessionId, append);
733752
onSubscribed?.();
734753
// Resume cursors bound durable history; later turns arrive through live events.
735754
// A null paginated cursor means there was no durable history at resume time.
@@ -789,17 +808,27 @@ export class CodexAcpClient {
789808
}
790809

791810
async newSession(request: acp.NewSessionRequest): Promise<SessionMetadata> {
811+
const append = readSessionInstructionAppend(request._meta);
812+
const custom = airCustomInstructions(request._meta);
813+
// Both extensions target developerInstructions. Never silently replace an
814+
// append with AIR's override; callers must choose one instruction contract.
815+
if (append !== undefined && custom !== undefined) {
816+
throw RequestError.invalidParams(undefined, "systemPrompt.append and AIR customInstructions cannot be combined");
817+
}
818+
const instructionOverride = await this.sessionInstructionOverride(append, request.cwd);
792819
const additionalDirectories = readAdditionalDirectories(request.cwd, request.additionalDirectories, request._meta);
793820
const developerInstructions = airCustomInstructions(request._meta);
794821
await this.refreshSkills(request.cwd, additionalDirectories);
795822

796823
const sessionConfig = await this.createSessionConfig(request.cwd, additionalDirectories, request.mcpServers);
797824
const response = await this.codexClient.threadStart({
825+
...instructionOverride,
798826
config: sessionConfig.config,
799827
modelProvider: this.getModelProvider(),
800828
cwd: request.cwd,
801829
...(developerInstructions !== undefined && {developerInstructions}),
802830
});
831+
this.recordInstructionAppend(response.thread.id, append);
803832

804833
const codexModels = await this.fetchAvailableModels();
805834
if (codexModels.length === 0) {
@@ -936,6 +965,37 @@ export class CodexAcpClient {
936965
return this.codexClient.mcpStartup.version();
937966
}
938967

968+
private recordInstructionAppend(sessionId: string, append: string | undefined): void {
969+
if (append === undefined) return;
970+
this.appliedInstructionAppends.set(sessionId, append);
971+
}
972+
973+
private async sessionInstructionOverride(append: string | undefined, cwd: string, sessionId?: string): Promise<{developerInstructions?: string}> {
974+
if (append === undefined) return {};
975+
if (sessionId !== undefined) {
976+
// Codex ignores instruction overrides for already-loaded threads, even
977+
// idle ones. Fail explicitly rather than claiming a role was applied.
978+
let cursor: string | undefined;
979+
do {
980+
const page = await this.codexClient.threadLoadedList({...(cursor !== undefined && {cursor})});
981+
if (page.data.includes(sessionId)) {
982+
if (this.appliedInstructionAppends.get(sessionId) === append) return {};
983+
throw RequestError.invalidParams(undefined, "Cannot append instructions to a loaded thread; close it before loading or resuming with instructions");
984+
}
985+
cursor = page.nextCursor ?? undefined;
986+
} while (cursor !== undefined);
987+
}
988+
const effective = await this.codexClient.configRead({cwd, includeLayers: false});
989+
// Read the effective project/user configuration, not restored thread text:
990+
// the latter may already include this append and would duplicate it on load.
991+
const configured = this.config["developer_instructions"] !== undefined
992+
? this.config["developer_instructions"] : effective.config.developer_instructions;
993+
if (configured != null && typeof configured !== "string") {
994+
throw RequestError.invalidParams(undefined, "Configured developer_instructions must be a string");
995+
}
996+
return {developerInstructions: configured ? (append ? `${configured}\n\n${append}` : configured) : append};
997+
}
998+
939999
private async createSessionConfig(
9401000
projectPath: string,
9411001
additionalDirectories: string[],

‎src/CodexAcpServer.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {readSessionInstructionAppend, SYSTEM_PROMPT_CAPABILITY} from "./SessionInstructions";
12
import * as acp from "@agentclientprotocol/sdk";
23
import {RequestError, type SessionId, type SessionModeState} from "@agentclientprotocol/sdk";
34
import {CodexEventHandler, type CompletedPlan} from "./CodexEventHandler";
@@ -516,6 +517,7 @@ export class CodexAcpServer {
516517
},
517518
authMethods: getCodexAuthMethods(_params.clientCapabilities),
518519
_meta: {
520+
systemPrompt: SYSTEM_PROMPT_CAPABILITY,
519521
steering: {
520522
supported: true,
521523
},
@@ -1155,6 +1157,7 @@ export class CodexAcpServer {
11551157
}
11561158

11571159
async loadSession(params: acp.LoadSessionRequest): Promise<LegacyLoadSessionResponse> {
1160+
readSessionInstructionAppend(params._meta);
11581161
return this.recovery === null
11591162
? await this.loadSessionOnce(params)
11601163
: await this.recovery.trackOpen(params.sessionId, () => this.loadSessionOnce(params));
@@ -1211,6 +1214,7 @@ export class CodexAcpServer {
12111214
}
12121215

12131216
async resumeSession(params: acp.ResumeSessionRequest): Promise<LegacyResumeSessionResponse> {
1217+
readSessionInstructionAppend(params._meta);
12141218
return this.recovery === null
12151219
? await this.resumeSessionOnce(params)
12161220
: await this.recovery.trackOpen(params.sessionId, () => this.resumeSessionOnce(params));
@@ -1238,6 +1242,7 @@ export class CodexAcpServer {
12381242
}
12391243

12401244
async forkSession(params: acp.ForkSessionRequest): Promise<acp.ForkSessionResponse> {
1245+
readSessionInstructionAppend(params._meta);
12411246
if (this.providerUpdate !== null) {
12421247
await this.waitForProviderUpdate();
12431248
}
@@ -1370,6 +1375,7 @@ export class CodexAcpServer {
13701375
async newSession(
13711376
params: acp.NewSessionRequest,
13721377
): Promise<LegacyNewSessionResponse> {
1378+
readSessionInstructionAppend(params._meta);
13731379
if (this.providerUpdate !== null) {
13741380
await this.waitForProviderUpdate();
13751381
}

‎src/JsonSnapshot.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ export class JsonText {
2828
}
2929

3030
/** Deeper values go to `JSON.stringify`, so that the walk does not use more stack than the serializer. */
31-
const MAX_DEPTH = 256;
31+
// Leave stack headroom for native JSON.stringify on Node/ARM64; a deep
32+
// subtree falls back before the recursive snapshot walk consumes its budget.
33+
const MAX_DEPTH = 64;
3234
const apply = Reflect.apply;
3335
const getPrototypeOf = Object.getPrototypeOf;
3436
/** `JSON.rawJSON` values serialize as their raw text. */

‎src/SessionFork.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {readSessionInstructionAppend} from "./SessionInstructions";
12
import {createHash} from "node:crypto";
23
import type * as acp from "@agentclientprotocol/sdk";
34
import {RequestError} from "@agentclientprotocol/sdk";
@@ -10,6 +11,7 @@ import type {SessionMetadata} from "./SessionMetadata";
1011

1112
export type SessionForkDependencies = {
1213
codexClient: CodexAppServerClient;
14+
sessionInstructionOverride(append: string | undefined, cwd: string): Promise<{developerInstructions?: string}>;
1315
refreshSkills(cwd: string, additionalDirectories: string[]): Promise<void>;
1416
createSessionConfig(
1517
cwd: string,
@@ -29,6 +31,8 @@ export async function forkSession(
2931
additionalDirectories: string[],
3032
dependencies: SessionForkDependencies,
3133
): Promise<SessionMetadata> {
34+
const append = readSessionInstructionAppend(request._meta);
35+
const instructionOverride = await dependencies.sessionInstructionOverride(append, request.cwd);
3236
await dependencies.refreshSkills(request.cwd, additionalDirectories);
3337
const lastTurnId = await resolveForkTurnId(request, dependencies.codexClient);
3438
const sessionConfig = await dependencies.createSessionConfig(
@@ -37,6 +41,7 @@ export async function forkSession(
3741
request.mcpServers ?? [],
3842
);
3943
const response = await dependencies.codexClient.threadFork({
44+
...instructionOverride,
4045
excludeTurns: true,
4146
config: sessionConfig.config,
4247
cwd: request.cwd,

‎src/SessionInstructions.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import {RequestError} from "@agentclientprotocol/sdk";
2+
3+
export const SYSTEM_PROMPT_CAPABILITY = {version: 1, append: true, clear: true, maxBytes: 256 * 1024};
4+
5+
/** Session metadata is an opt-in append, never a replacement of Codex's base prompt. */
6+
export function readSessionInstructionAppend(meta?: Record<string, unknown> | null): string | undefined {
7+
const prompt = meta?.["systemPrompt"];
8+
if (prompt === undefined) return undefined;
9+
if (prompt === null || typeof prompt !== "object" || Array.isArray(prompt)
10+
|| Object.keys(prompt).some(key => key !== "append")
11+
|| !("append" in prompt) || typeof prompt.append !== "string") {
12+
throw RequestError.invalidParams(undefined, "systemPrompt must contain only an append string");
13+
}
14+
if (Buffer.byteLength(prompt.append, "utf8") > SYSTEM_PROMPT_CAPABILITY.maxBytes) {
15+
throw RequestError.invalidParams(undefined, `systemPrompt.append exceeds ${SYSTEM_PROMPT_CAPABILITY.maxBytes} UTF-8 bytes`);
16+
}
17+
// Explicit empty append resets the per-session addition to configured rules.
18+
// Omitted metadata still preserves native history without an override.
19+
return prompt.append;
20+
}

‎src/__tests__/CodexACPAgent/agent-file-change-report.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {realpathSync} from "node:fs";
12
import {beforeEach, describe, expect, it, vi} from "vitest";
23
import * as acp from "@agentclientprotocol/sdk";
34
import {
@@ -11,6 +12,9 @@ import {logger} from "../../Logger";
1112
import type {Turn, TurnCompletedNotification} from "../../app-server/v2";
1213
import {AGENT_FILE_CHANGE_REPORT_MAX_DIFF_BYTES} from "../../AgentFileChangeReport";
1314

15+
// Use a real fixture root: /workspace may be a symlink on the test host.
16+
const reportWorkspace = realpathSync(process.cwd());
17+
1418
function createTurn(id: string, status: Turn["status"]): Turn {
1519
return {
1620
id,
@@ -73,7 +77,7 @@ async function setupMainPrompt(negotiateCapability = true): Promise<{
7377
...(negotiateCapability ? {clientCapabilities: FILE_CHANGE_REPORT_CLIENT_CAPABILITIES} : {}),
7478
});
7579
const sessionState = createTestSessionState({
76-
cwd: "/workspace",
80+
cwd: reportWorkspace,
7781
additionalDirectories: ["/generated"],
7882
});
7983
vi.spyOn(fixture.getCodexAcpAgent(), "getSessionState").mockReturnValue(sessionState);
@@ -134,7 +138,7 @@ describe("agent file-change report lifecycle", () => {
134138
version: 1,
135139
requestId: "request-42",
136140
status: "reported",
137-
paths: ["/workspace/src/Main.kt"],
141+
paths: [`${reportWorkspace}/src/Main.kt`],
138142
declaredComplete: false,
139143
truncated: false,
140144
uncertainty: "Codex turn diffs may omit same-content renames and changes made outside apply_patch, including shell commands, version-control commands, generators, and child processes.",
@@ -164,7 +168,7 @@ describe("agent file-change report lifecycle", () => {
164168
);
165169

166170
expect(reportedUpdates(fixture)[0]).toMatchObject({
167-
_meta: {jetbrains: {air: {agentFileChangeReport: {paths: ["/workspace/final.txt"]}}}},
171+
_meta: {jetbrains: {air: {agentFileChangeReport: {paths: [`${reportWorkspace}/final.txt`]}}}},
168172
});
169173
});
170174

0 commit comments

Comments
 (0)