-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathcodex-app-server-agent.ts
More file actions
1704 lines (1613 loc) · 59.7 KB
/
Copy pathcodex-app-server-agent.ts
File metadata and controls
1704 lines (1613 loc) · 59.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
AgentSideConnection,
ForkSessionRequest,
ForkSessionResponse,
InitializeRequest,
InitializeResponse,
ListSessionsRequest,
ListSessionsResponse,
LoadSessionRequest,
LoadSessionResponse,
NewSessionRequest,
NewSessionResponse,
PromptRequest,
PromptResponse,
RequestPermissionResponse,
ResumeSessionRequest,
ResumeSessionResponse,
SetSessionConfigOptionRequest,
SetSessionConfigOptionResponse,
StopReason,
} from "@agentclientprotocol/sdk";
import { mcpToolKey, posthogToolMeta } from "@posthog/shared";
import {
type NativeGoalState,
POSTHOG_NOTIFICATIONS,
} from "../../acp-extensions";
import { DEFAULT_CODEX_MODEL } from "../../gateway-models";
import type { ProcessSpawnedCallback } from "../../types";
import { ALLOW_BYPASS } from "../../utils/common";
import { Logger } from "../../utils/logger";
import {
nodeReadableToWebReadable,
nodeWritableToWebWritable,
} from "../../utils/streams";
import { BaseAcpAgent, type BaseSettingsManager } from "../base-acp-agent";
import {
type ContextBreakdownBaseline,
emptyBaseline,
estimateTokens,
} from "../claude/context-breakdown";
import { isLocalSkillCommandChunk } from "../local-skill";
import { resolveSpokenNarration } from "../session-meta";
import {
AppServerClient,
type AppServerClientHandlers,
type AppServerRpc,
} from "./app-server-client";
import { handleServerRequest } from "./approvals";
import {
type AccumulatedUsage,
buildSdkSessionParams,
buildTurnCompleteParams,
buildUsageBreakdownParams,
} from "./ext-notifications";
import { type CodexUserInput, toCodexInput } from "./input";
import { buildLocalToolsServer, type LocalToolsMeta } from "./local-tools-mcp";
import {
type AppServerItem,
changePaths,
diffContent,
mapAppServerNotification,
mapHistoryItem,
} from "./mapping";
import { toCodexMcpServers } from "./mcp-config";
import { McpManager } from "./mcp-manager";
import {
APP_SERVER_METHODS,
APP_SERVER_NOTIFICATIONS,
APP_SERVER_REQUESTS,
} from "./protocol";
import { type CodexSandboxPolicy, SessionConfigState } from "./session-config";
import {
type CodexAppServerProcess,
type CodexAppServerProcessOptions,
spawnCodexAppServerProcess,
} from "./spawn";
import { parseStructuredOutput } from "./structured-output";
import { TurnController } from "./turn-controller";
import { UsageTracker } from "./usage-tracker";
type AppServerSessionMeta = {
// The host sends either a plain string or the Claude-style `{ append }` form.
systemPrompt?: string | { append?: string };
jsonSchema?: Record<string, unknown> | null;
permissionMode?: string;
taskRunId?: string;
taskId?: string;
persistence?: { taskId?: string };
environment?: "local" | "cloud";
channelMode?: boolean;
spokenNarration?: boolean;
baseBranch?: string;
nativeGoal?: NativeGoalState;
};
/** The subset of codex's `Thread` the adapter reads: id + persisted `turns` for history replay. */
type AppServerThread = {
id?: string;
turns?: Array<{ items?: Parameters<typeof mapHistoryItem>[1][] }>;
};
type ThreadGoal = {
objective: string;
status: NativeGoalState["status"];
};
type GoalCommand =
| { kind: "get" }
| { kind: "clear" }
| { kind: "pause" }
| { kind: "resume" }
| { kind: "set"; objective: string };
type CodexSkill = {
name?: string;
description?: string;
enabled?: boolean;
};
const GOAL_COMMAND = {
name: "goal",
description: "Set or view the goal for a long-running task",
input: { hint: "[<objective>|clear|pause|resume]" },
};
function isHiddenPromptBlock(block: PromptRequest["prompt"][number]): boolean {
const meta = block._meta as { ui?: { hidden?: boolean } } | undefined;
return meta?.ui?.hidden === true;
}
function visiblePromptBlocks(
prompt: PromptRequest["prompt"],
): PromptRequest["prompt"] {
return prompt.filter((block) => !isHiddenPromptBlock(block));
}
function parseGoalCommand(prompt: PromptRequest["prompt"]): GoalCommand | null {
const visible = visiblePromptBlocks(prompt);
if (visible.some((block) => block.type !== "text")) return null;
const text = visible
.map((block) => (block.type === "text" ? block.text : ""))
.join("\n")
.trim();
const match = text.match(/^\/goal(?:\s+([\s\S]*))?$/);
if (!match) return null;
const argument = match[1]?.trim();
if (!argument) return { kind: "get" };
switch (argument.toLowerCase()) {
case "clear":
return { kind: "clear" };
case "pause":
return { kind: "pause" };
case "resume":
return { kind: "resume" };
default:
return { kind: "set", objective: argument };
}
}
// The native app-server owns its config; BaseAcpAgent only calls dispose() on this.
class NoopSettingsManager implements BaseSettingsManager {
constructor(private cwd: string) {}
dispose(): void {}
getCwd(): string {
return this.cwd;
}
async setCwd(cwd: string): Promise<void> {
this.cwd = cwd;
}
async initialize(): Promise<void> {}
}
export interface CodexAppServerAgentOptions {
processOptions: CodexAppServerProcessOptions;
model?: string;
reasoningEffort?: string;
/** Models outside the org's plan; the picker renders them locked. */
restrictedModelIds?: ReadonlySet<string>;
processCallbacks?: ProcessSpawnedCallback;
logger?: Logger;
onStructuredOutput?: (output: Record<string, unknown>) => Promise<void>;
/** Test seam: build the JSON-RPC client (defaults to spawning the process). */
rpcFactory?: (handlers: AppServerClientHandlers) => AppServerRpc;
}
/**
* ACP Agent backed by the native Codex `app-server` JSON-RPC protocol,
* presenting the ACP surface PostHog Code expects.
*/
export class CodexAppServerAgent extends BaseAcpAgent {
readonly adapterName = "codex";
private readonly rpc: AppServerRpc;
private readonly proc?: CodexAppServerProcess;
private readonly config: SessionConfigState;
private readonly onStructuredOutput?: (
output: Record<string, unknown>,
) => Promise<void>;
/** Codex-specific guidance injected at spawn time; replayed per-thread. */
private readonly developerInstructions?: string;
private threadId?: string;
/** JSON schema constraining the final message; set per session via `_meta`. */
private jsonSchema?: Record<string, unknown>;
/** Final assistant message text for the in-flight turn (structured output). */
private lastAgentMessage = "";
/** True between a contextCompaction item's start and its boundary (dedupes the boundary). */
private compactionActive = false;
/** Maps the host's taskRunId to this session, replayed for cloud notifications. */
private taskRunId?: string;
/** Deployment environment; on "cloud" a non-danger sandbox would panic, so we skip the override. */
private environment?: "local" | "cloud";
private readonly commandOutputs = new Map<string, string>();
/** Extra writable roots for this session, folded into workspaceWrite sandbox turns. */
private additionalDirectories?: string[];
/** The session workspace stays writable when extra roots are applied per turn. */
private workspaceDirectory?: string;
/** The in-flight turn's <proposed_plan>, streamed or completed (drives the implement handoff). */
private planProposal?: { itemId: string; text: string };
/** Idle signal deferred while the plan handoff keeps this prompt busy. */
private deferredTurnComplete?: { usage: AccumulatedUsage };
/** Settles the pending plan-approval race on cancel/close/preempting prompt. */
private planHandoffCancel?: () => void;
private readonly mcp = new McpManager();
private readonly turns = new TurnController();
private readonly usage = new UsageTracker();
/** Pause/clear can race a goal continuation already queued by app-server. */
private cancelNextGoalTurn = false;
/** Native goal ticks start outside prompt(), so TurnController does not own them. */
private nativeGoalTurnId?: string;
constructor(
client: AgentSideConnection,
options: CodexAppServerAgentOptions,
) {
super(client);
this.logger =
options.logger ??
new Logger({ debug: true, prefix: "[CodexAppServerAgent]" });
this.config = new SessionConfigState(
options.model ?? DEFAULT_CODEX_MODEL,
options.reasoningEffort,
options.restrictedModelIds,
);
this.onStructuredOutput = options.onStructuredOutput;
this.developerInstructions = options.processOptions.developerInstructions;
const handlers: AppServerClientHandlers = {
logger: this.logger,
onNotification: (method, params) =>
this.handleNotification(method, params),
onRequest: (method, params) => this.handleApproval(method, params),
onClose: () => this.handleServerClosed(),
};
if (options.rpcFactory) {
this.rpc = options.rpcFactory(handlers);
} else {
this.proc = spawnCodexAppServerProcess({
...options.processOptions,
logger: this.logger,
processCallbacks: options.processCallbacks,
});
this.rpc = new AppServerClient(
{
readable: nodeReadableToWebReadable(this.proc.stdout),
writable: nodeWritableToWebWritable(this.proc.stdin),
},
handlers,
);
}
this.session = {
abortController: new AbortController(),
settingsManager: new NoopSettingsManager(
options.processOptions.cwd ?? process.cwd(),
),
notificationHistory: [],
cancelled: false,
};
}
async initialize(request: InitializeRequest): Promise<InitializeResponse> {
await this.rpc.request(APP_SERVER_METHODS.INITIALIZE, {
clientInfo: {
name: "posthog-code",
title: "PostHog Code",
version: "0.1.0",
},
// Opt into codex's experimental API so experimental turn/start fields are honored.
capabilities: { experimentalApi: true, requestAttestation: false },
});
this.rpc.notify(APP_SERVER_NOTIFICATIONS.INITIALIZED, {});
return {
protocolVersion: request.protocolVersion,
agentCapabilities: {
promptCapabilities: {
image: true,
embeddedContext: true,
},
// Only http: we don't claim SSE rather than mistranslate it into the http shape.
mcpCapabilities: {
http: true,
},
loadSession: true,
sessionCapabilities: {
list: {},
fork: {},
resume: {},
additionalDirectories: {},
},
_meta: {
posthog: {
resumeSession: true,
steering: "native",
},
},
},
agentInfo: {
name: "codex",
title: "Codex (app-server)",
version: "0.1.0",
},
authMethods: [],
};
}
async newSession(params: NewSessionRequest): Promise<NewSessionResponse> {
const { threadId } = await this.setupThread(
APP_SERVER_METHODS.THREAD_START,
{
cwd: params.cwd,
mcpServers: params.mcpServers,
meta: params._meta as AppServerSessionMeta | undefined,
additionalDirectories: params.additionalDirectories ?? undefined,
},
);
return { sessionId: threadId, configOptions: this.config.options };
}
async resumeSession(
params: ResumeSessionRequest,
): Promise<ResumeSessionResponse> {
await this.setupThread(APP_SERVER_METHODS.THREAD_RESUME, {
cwd: params.cwd,
mcpServers: params.mcpServers,
meta: params._meta as AppServerSessionMeta | undefined,
threadId: params.sessionId,
additionalDirectories: params.additionalDirectories ?? undefined,
});
return { configOptions: this.config.options };
}
/** Re-attach to an existing thread without starting a turn: resume it, then replay the transcript. */
async loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse> {
const { thread } = await this.setupThread(
APP_SERVER_METHODS.THREAD_RESUME,
{
cwd: params.cwd,
mcpServers: params.mcpServers,
meta: params._meta as AppServerSessionMeta | undefined,
threadId: params.sessionId,
additionalDirectories: params.additionalDirectories ?? undefined,
},
);
this.replayHistory(thread);
return { configOptions: this.config.options };
}
async unstable_forkSession(
params: ForkSessionRequest,
): Promise<ForkSessionResponse> {
const { threadId } = await this.setupThread(
APP_SERVER_METHODS.THREAD_FORK,
{
cwd: params.cwd,
mcpServers: params.mcpServers,
meta: params._meta as AppServerSessionMeta | undefined,
threadId: params.sessionId,
additionalDirectories: params.additionalDirectories ?? undefined,
},
);
return { sessionId: threadId, configOptions: this.config.options };
}
/** Replay a resumed thread's persisted turns (from the thread/resume response) as session updates. */
private replayHistory(thread: AppServerThread | undefined): void {
if (!this.sessionId || !thread?.turns?.length) return;
for (const turn of thread.turns) {
for (const item of turn.items ?? []) {
for (const update of mapHistoryItem(this.sessionId, item)) {
void this.client.sessionUpdate(update).catch(() => undefined);
}
}
}
}
async listSessions(
params: ListSessionsRequest,
): Promise<ListSessionsResponse> {
try {
const res = await this.rpc.request<{
data?: Array<{
id?: string;
cwd?: string;
name?: string | null;
preview?: string;
}>;
}>(APP_SERVER_METHODS.THREAD_LIST, { cwd: params.cwd });
const sessions = (res?.data ?? [])
.filter((t) => t?.id)
.map((t) => ({
sessionId: t.id as string,
cwd: t.cwd ?? params.cwd ?? "",
...(t.name || t.preview
? { title: t.name ?? t.preview ?? undefined }
: {}),
}));
return { sessions };
} catch (err) {
this.logger.warn("thread/list failed", { error: String(err) });
return { sessions: [] };
}
}
/** Shared thread setup for start/resume/fork. `threadId` present => resume/fork; absent => new thread. */
private async setupThread(
method: string,
params: {
cwd?: string;
mcpServers?: NewSessionRequest["mcpServers"];
meta?: AppServerSessionMeta;
threadId?: string;
additionalDirectories?: string[];
},
): Promise<{ threadId: string; thread: AppServerThread | undefined }> {
this.cancelNextGoalTurn = false;
this.nativeGoalTurnId = undefined;
this.jsonSchema = params.meta?.jsonSchema ?? undefined;
this.taskRunId = params.meta?.taskRunId;
this.environment = params.meta?.environment;
this.additionalDirectories = params.additionalDirectories;
this.workspaceDirectory = params.cwd;
this.config.setInitialMode(params.meta?.permissionMode);
// Codex doesn't attribute input tokens by source; the baseline seeds the resident floor + system prompt.
this.usage.setBaseline(buildBaseline(params.meta));
// Flatten the {append} form (else "[object Object]") and dedupe identical parts
// (the host pre-flattens into developerInstructions, so the prod prompt would duplicate).
const developerInstructions = [
...new Set(
[
this.developerInstructions,
flattenSystemPrompt(params.meta?.systemPrompt),
].filter((s): s is string => !!s),
),
].join("\n\n");
// Degrade gracefully: an unresolvable bundled local-tools script skips it with a
// warning rather than killing thread setup.
let localTools: ReturnType<typeof buildLocalToolsServer> = null;
try {
localTools = buildLocalToolsServer(
{ cwd: params.cwd },
this.localToolsMeta(params.meta),
);
} catch (err) {
this.logger.warn(
"local-tools server unavailable; continuing without it",
{ error: String(err) },
);
}
const mcpServers = toCodexMcpServers([
...(params.mcpServers ?? []),
...(localTools ? [localTools] : []),
]);
const config = buildThreadConfig(mcpServers, params.additionalDirectories);
const result = await this.rpc.request<{ thread?: AppServerThread }>(
method,
{
model: this.config.model,
cwd: params.cwd,
...(params.threadId ? { threadId: params.threadId } : {}),
...(developerInstructions ? { developerInstructions } : {}),
...(config ? { config } : {}),
},
);
const thread = result?.thread;
const threadId = thread?.id ?? params.threadId;
if (!threadId) {
throw new Error(`codex app-server ${method} returned no thread id`);
}
this.threadId = threadId;
this.sessionId = threadId;
if (method === APP_SERVER_METHODS.THREAD_START && params.meta?.nativeGoal) {
await this.restoreGoal(params.meta.nativeGoal);
}
await this.loadModelConfig();
this.emitConfigOptions();
await this.emitAvailableCommands();
await this.emitSdkSession();
this.logger.info("Codex app-server thread ready", {
method,
threadId,
mcpServers: mcpServers ? Object.keys(mcpServers) : [],
hasOutputSchema: !!this.jsonSchema,
hasLocalTools: !!localTools,
});
return { threadId, thread };
}
private localToolsMeta(
meta: AppServerSessionMeta | undefined,
): LocalToolsMeta | undefined {
if (!meta) return undefined;
return {
environment: meta.environment,
channelMode: meta.channelMode,
spokenNarration: resolveSpokenNarration(meta),
taskId: meta.taskId,
taskRunId: meta.taskRunId,
persistence: meta.persistence,
baseBranch: meta.baseBranch,
};
}
private async emitSdkSession(): Promise<void> {
if (!this.taskRunId || !this.sessionId) return;
await this.client
.extNotification(
POSTHOG_NOTIFICATIONS.SDK_SESSION,
buildSdkSessionParams(
this.sessionId,
this.taskRunId,
) as unknown as Record<string, unknown>,
)
.catch((err) =>
this.logger.warn("sdk_session extNotification failed", err),
);
}
async setSessionConfigOption(
params: SetSessionConfigOptionRequest,
): Promise<SetSessionConfigOptionResponse> {
const { configId } = params as { configId?: string };
const value = (params as { value?: unknown }).value;
const { modeChanged } = this.config.setOption(configId, value);
// collaborationMode rides the next turn/start, so a mode switch only needs current_mode_update here.
if (modeChanged) {
this.emitCurrentMode(this.config.mode);
if (this.config.mode !== "plan") this.planHandoffCancel?.();
}
this.emitConfigOptions();
return { configOptions: this.config.options };
}
/** Emit current_mode_update on mode change for the host's mode cache. */
private emitCurrentMode(modeId: string): void {
if (!this.sessionId) return;
void this.client
.sessionUpdate({
sessionId: this.sessionId,
update: { sessionUpdate: "current_mode_update", currentModeId: modeId },
} as unknown as Parameters<AgentSideConnection["sessionUpdate"]>[0])
.catch(() => undefined);
}
private async loadModelConfig(): Promise<void> {
try {
const res = await this.rpc.request<{ data?: any[] }>(
APP_SERVER_METHODS.MODEL_LIST,
{},
);
this.config.loadModels(res?.data ?? []);
} catch (err) {
this.logger.warn("model/list failed; using current model only", {
error: String(err),
});
this.config.clearModels();
}
}
private emitConfigOptions(): void {
if (!this.sessionId) return;
void this.client
.sessionUpdate({
sessionId: this.sessionId,
update: {
sessionUpdate: "config_option_update",
configOptions: this.config.options,
},
} as unknown as Parameters<AgentSideConnection["sessionUpdate"]>[0])
.catch((err) => this.logger.warn("config_option_update failed", err));
}
/** skills/list → available_commands_update so the slash-command menu fills. */
private async emitAvailableCommands(): Promise<void> {
if (!this.sessionId) return;
let commands: Array<{
name: string;
description: string;
input?: { hint: string };
}> = [GOAL_COMMAND];
try {
const res = await this.rpc.request<{
data?: Array<{ skills?: CodexSkill[] }>;
}>(APP_SERVER_METHODS.SKILLS_LIST, {});
const skills = (res?.data ?? [])
.flatMap((entry) => entry?.skills ?? [])
// Drop explicitly-disabled skills; lenient `!== false` so a malformed payload still shows.
.filter(
(skill): skill is CodexSkill & { name: string } =>
!!skill.name &&
skill.name !== GOAL_COMMAND.name &&
skill.enabled !== false,
)
.map((skill) => ({
name: skill.name,
description: skill.description ?? "",
}));
commands = [GOAL_COMMAND, ...skills];
} catch (err) {
this.logger.warn("skills/list failed", { error: String(err) });
}
void this.client
.sessionUpdate({
sessionId: this.sessionId,
update: {
sessionUpdate: "available_commands_update",
availableCommands: commands,
},
} as unknown as Parameters<AgentSideConnection["sessionUpdate"]>[0])
.catch(() => undefined);
}
async prompt(params: PromptRequest): Promise<PromptResponse> {
if (!this.threadId) {
throw new Error("prompt() called before newSession()");
}
const goalCommand = parseGoalCommand(params.prompt);
if (goalCommand) {
this.broadcastUserInput(visiblePromptBlocks(params.prompt));
await this.handleGoalCommand(goalCommand);
return { stopReason: "end_turn" };
}
this.cancelNextGoalTurn = false;
// Reopen the notification gate (a prior interrupt may have left session.cancelled set).
this.session.cancelled = false;
// A new prompt while the plan handoff awaits approval implicitly declines it:
// settle the race so the previous prompt() returns and this one owns the turn.
this.planHandoffCancel?.();
// Prepend _meta.prContext (host PR-follow-up / Slack runs) to the FORWARDED prompt,
// else codex cloud follow-ups lose the PR-review context. The echo omits it.
const meta = params._meta as
| {
prContext?: unknown;
localSkillContext?: unknown;
localSkillName?: unknown;
}
| undefined;
const prContext = meta?.prContext;
// Inline installed local skill definitions (mirrors the Claude adapter):
// codex's skill catalog is fixed at thread start, so mid-session installs
// are invisible without this. A bare `/name` command chunk is dropped —
// the injected context already carries the user's args.
const localSkillContext =
typeof meta?.localSkillContext === "string"
? meta.localSkillContext
: null;
const localSkillName =
typeof meta?.localSkillName === "string" ? meta.localSkillName : null;
let forwarded = params.prompt;
if (localSkillContext) {
if (localSkillName) {
let skippedLocalSkillCommand = false;
forwarded = forwarded.filter((chunk) => {
if (
!skippedLocalSkillCommand &&
isLocalSkillCommandChunk(chunk, localSkillName)
) {
skippedLocalSkillCommand = true;
return false;
}
return true;
});
}
forwarded = [
{ type: "text" as const, text: localSkillContext },
...forwarded,
];
}
const promptBlocks =
typeof prContext === "string" && prContext.length > 0
? [{ type: "text" as const, text: prContext }, ...forwarded]
: forwarded;
const input = toCodexInput(promptBlocks);
if (input.length === 0) {
// turn/start rejects empty input, so end the turn cleanly.
this.logger.warn("prompt() had no usable input blocks; ending turn");
return { stopReason: "end_turn" };
}
// Count by type (not input.length): a resource block can fan out to multiple blocks.
const dropped = params.prompt.filter(
(b) =>
b.type !== "text" &&
b.type !== "image" &&
b.type !== "resource" &&
b.type !== "resource_link",
).length;
if (dropped > 0) {
this.logger.warn("Dropped non-text/non-image prompt blocks", { dropped });
}
// Echo the user prompt (codex emits none), for fresh turns and steering alike.
this.broadcastUserInput(params.prompt);
if (this.turns.isRunning) {
// A turn is already running: fold the message in via turn/steer (precondition: the
// active turnId). Refresh from the response's rotated turnId so a later steer/interrupt
// still targets the live turn (no turn/started is re-emitted for a steer).
const steerRes = await this.rpc
.request<{ turnId?: string }>(APP_SERVER_METHODS.TURN_STEER, {
threadId: this.threadId,
input,
expectedTurnId: this.turns.activeTurnId,
})
.catch((err) => {
this.logger.warn("turn/steer failed", err);
return undefined;
});
this.turns.onSteered(steerRes?.turnId);
return { stopReason: await this.turns.awaitCompletion() };
}
if (this.turns.isPending) {
// A turn is pending but has no turnId yet, so we can't steer; fail fast.
throw new Error("prompt() called while a turn is already in progress");
}
const stopReason = await this.runTurn(input);
return { stopReason: await this.maybeOfferPlanImplementation(stopReason) };
}
private async handleGoalCommand(command: GoalCommand): Promise<void> {
if (!this.threadId) return;
if (command.kind === "clear") {
this.cancelNextGoalTurn = true;
const result = await this.rpc.request<{ cleared?: boolean }>(
APP_SERVER_METHODS.THREAD_GOAL_CLEAR,
{ threadId: this.threadId },
);
await this.emitGoalState(null);
await this.cancelRunningGoalTurn();
this.broadcastAgentText(
result.cleared ? "Goal cleared." : "No goal was set.",
);
return;
}
if (command.kind === "get") {
const result = await this.rpc.request<{ goal?: ThreadGoal | null }>(
APP_SERVER_METHODS.THREAD_GOAL_GET,
{ threadId: this.threadId },
);
this.broadcastAgentText(
result.goal
? `Goal ${result.goal.status}: ${result.goal.objective}`
: "No goal set. Usage: `/goal <objective>`",
);
return;
}
if (command.kind === "pause") {
this.cancelNextGoalTurn = true;
}
const params =
command.kind === "set"
? { threadId: this.threadId, objective: command.objective }
: {
threadId: this.threadId,
status: command.kind === "pause" ? "paused" : "active",
};
const result = await this.rpc.request<{ goal: ThreadGoal }>(
APP_SERVER_METHODS.THREAD_GOAL_SET,
params,
);
await this.emitGoalState(result.goal);
if (command.kind === "pause") {
await this.cancelRunningGoalTurn();
}
const prefix =
command.kind === "set"
? "Goal set"
: command.kind === "pause"
? "Goal paused"
: "Goal resumed";
this.broadcastAgentText(`${prefix}: ${result.goal.objective}`);
}
private async restoreGoal(goal: NativeGoalState): Promise<void> {
if (!this.threadId) return;
const result = await this.rpc.request<{ goal: ThreadGoal }>(
APP_SERVER_METHODS.THREAD_GOAL_SET,
{
threadId: this.threadId,
objective: goal.objective,
status: goal.status,
},
);
await this.emitGoalState(result.goal);
}
private async emitGoalState(goal: NativeGoalState | null): Promise<void> {
await this.client
.extNotification(POSTHOG_NOTIFICATIONS.CODEX_GOAL, { goal })
.catch((error) =>
this.logger.warn("Failed to persist Codex goal state", error),
);
}
private async cancelRunningGoalTurn(): Promise<void> {
if (this.turns.isRunning) {
this.cancelNextGoalTurn = false;
await this.interrupt();
return;
}
if (this.nativeGoalTurnId) {
await this.interruptNativeGoalTurn(this.nativeGoalTurnId);
}
}
private interruptQueuedGoalTurn(turnId: string | undefined): void {
if (!this.cancelNextGoalTurn || !this.threadId || !turnId) return;
void this.interruptNativeGoalTurn(turnId);
}
private async interruptNativeGoalTurn(turnId: string): Promise<void> {
if (!this.threadId) return;
await this.rpc
.request(APP_SERVER_METHODS.TURN_INTERRUPT, {
threadId: this.threadId,
turnId,
})
.then(() => {
this.cancelNextGoalTurn = false;
if (this.nativeGoalTurnId === turnId) {
this.nativeGoalTurnId = undefined;
}
})
.catch((error) =>
this.logger.warn("Native goal turn interrupt failed", error),
);
}
/** Start one codex turn and await its completion. */
private async runTurn(input: CodexUserInput[]): Promise<StopReason> {
this.lastAgentMessage = "";
this.resetUsage();
this.planProposal = undefined;
// A new turn owns the idle boundary; its own completion emits the signal.
this.deferredTurnComplete = undefined;
const { completion, turn } = this.turns.begin();
try {
const approvalPolicy = this.config.approvalPolicy();
const sandboxPolicy = this.sandboxPolicyForTurn();
await this.rpc.request(APP_SERVER_METHODS.TURN_START, {
threadId: this.threadId,
input,
model: this.config.model,
...(this.config.effort ? { effort: this.config.effort } : {}),
// Always request a reasoning summary; the default "auto" can skip it on trivial turns.
summary: "detailed",
// Picker preset applied per-turn. codex keeps turn overrides for subsequent turns,
// so every mode sends its full policy — omitting a field would leave the previous
// mode's value active (e.g. plan's readOnly sandbox bleeding into auto).
...(approvalPolicy ? { approvalPolicy } : {}),
// Pushed every turn — codex remembers the last mode, so switching back from plan must be explicit.
collaborationMode: this.config.collaborationModeForTurn(),
// Skipped on cloud, where a non-danger sandbox re-engages the unavailable
// linux-sandbox and panics; the enclosing docker/Modal sandbox isolates instead.
...(this.environment !== "cloud" && sandboxPolicy
? { sandboxPolicy }
: {}),
// Constrain the final message to the task schema for parseable structured output.
...(this.jsonSchema ? { outputSchema: this.jsonSchema } : {}),
});
return await completion;
} finally {
this.turns.finishPrompt(turn);
}
}
/**
* codex plan mode finalizes with a <proposed_plan> item and (by design) never
* asks "should I proceed?" — the client owns the handoff. Mirror the Claude
* ExitPlanMode flow: offer to implement; on accept switch the mode and run
* the implementation turn inside the same prompt() call. Plan feedback loops
* back into another plan turn, whose revised plan prompts again.
*/
private async maybeOfferPlanImplementation(
stopReason: StopReason,
): Promise<StopReason> {
let reason = stopReason;
try {
while (
reason === "end_turn" &&
this.config.mode === "plan" &&
this.planProposal &&
!this.session.cancelled
) {
const proposal = this.planProposal;
this.planProposal = undefined;
const outcome = await this.requestPlanImplementation(proposal);
// Re-check after the await: a cancel that raced the response wins, so a
// late accept can never start implementation on a cancelled prompt.
if (this.session.cancelled) {
reason = "cancelled";
break;
}
// A picker change while approval was open owns the mode. Never let a
// stale approval overwrite it with a broader implementation mode.
if (this.config.mode !== "plan") break;
if (outcome.kind === "implement") {
this.config.setOption("mode", outcome.mode);
this.emitCurrentMode(outcome.mode);
this.emitConfigOptions();
reason = await this.runFollowUpTurn(IMPLEMENT_PLAN_MESSAGE);
break;
}
if (outcome.kind === "feedback") {
reason = await this.runFollowUpTurn(outcome.feedback);
continue;
}
break;
}
} finally {
await this.flushDeferredTurnComplete(reason);
}
return reason;
}
/**
* Emit the idle signal the handoff's plan turn deferred, unless a newer turn
* took over the boundary (a follow-up turn clears the deferral in runTurn and
* emits its own completion; a preempting prompt() does the same).
*/
private async flushDeferredTurnComplete(reason: StopReason): Promise<void> {
const deferred = this.deferredTurnComplete;
this.deferredTurnComplete = undefined;
if (!deferred || this.turns.isPending) return;
await this.emitTurnCompleteSignal(reason, deferred.usage);
}
/** Run an adapter-initiated turn, echoed as a user message like a host prompt. */
private async runFollowUpTurn(text: string): Promise<StopReason> {
this.broadcastUserInput([{ type: "text", text }]);
return this.runTurn(toCodexInput([{ type: "text", text }]));
}
/**
* The ExitPlanMode-style approval: a switch_mode tool call (routes the host
* to its plan-approval UI) whose option ids are codex mode ids. Cancel or a
* failed prompt stays in plan mode — never silently start implementing.
*/
private async requestPlanImplementation(proposal: {
itemId: string;
text: string;
}): Promise<
| { kind: "implement"; mode: "auto" | "full-access" }
| { kind: "feedback"; feedback: string }
| { kind: "stay" }
> {
const toolCallId = `${proposal.itemId}:implement`;
const toolCall = {
toolCallId,
title: "Ready to code?",
kind: "switch_mode",
content: [
{
type: "content" as const,
content: { type: "text" as const, text: proposal.text },
},
],
rawInput: { plan: proposal.text },
};
const options = [
{
optionId: "auto",
name: 'Yes, and use "auto" mode',
kind: "allow_always" as const,
},
...(ALLOW_BYPASS
? [
{
optionId: "full-access",
name: "Yes, and auto-approve everything",
kind: "allow_always" as const,
},
]
: []),
{
optionId: "reject_with_feedback",
name: "No, and tell Codex what to do differently",
kind: "reject_once" as const,
_meta: { customInput: true },