stitchkit 0.129.0 → 0.130.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/dist/agent-executor/acp/v1-connect.d.ts +87 -19
- package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-driver.d.ts +4 -2
- package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-handlers.d.ts +56 -0
- package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-map.d.ts +13 -2
- package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-permission.d.ts +44 -0
- package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-protocol.d.ts +63 -10
- package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-session.d.ts +34 -7
- package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-turn.d.ts +51 -13
- package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
- package/dist/agent-executor/claude/classify.d.ts +10 -0
- package/dist/agent-executor/claude/classify.d.ts.map +1 -1
- package/dist/agent-executor/claude/cli-driver.d.ts +4 -1
- package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
- package/dist/agent-executor/claude/events.d.ts +146 -0
- package/dist/agent-executor/claude/events.d.ts.map +1 -0
- package/dist/agent-executor/claude/limits.d.ts +7 -1
- package/dist/agent-executor/claude/limits.d.ts.map +1 -1
- package/dist/agent-executor/claude/protocol.d.ts +49 -9
- package/dist/agent-executor/claude/protocol.d.ts.map +1 -1
- package/dist/agent-executor/claude/session.d.ts +2 -0
- package/dist/agent-executor/claude/session.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/controls.d.ts +10 -1
- package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/driver.d.ts +97 -3
- package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/probe.d.ts +29 -0
- package/dist/agent-executor/claude-sdk/probe.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/query-loop.d.ts +53 -5
- package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/query-options.d.ts +2 -0
- package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/session.d.ts +2 -3
- package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/turn-usage.d.ts +81 -0
- package/dist/agent-executor/claude-sdk/turn-usage.d.ts.map +1 -0
- package/dist/agent-executor/codex/classify.d.ts +4 -0
- package/dist/agent-executor/codex/classify.d.ts.map +1 -1
- package/dist/agent-executor/codex/connect.d.ts +5 -2
- package/dist/agent-executor/codex/connect.d.ts.map +1 -1
- package/dist/agent-executor/codex/control-client.d.ts +206 -0
- package/dist/agent-executor/codex/control-client.d.ts.map +1 -0
- package/dist/agent-executor/codex/driver.d.ts +35 -5
- package/dist/agent-executor/codex/driver.d.ts.map +1 -1
- package/dist/agent-executor/codex/handlers.d.ts +52 -0
- package/dist/agent-executor/codex/handlers.d.ts.map +1 -0
- package/dist/agent-executor/codex/limits.d.ts.map +1 -1
- package/dist/agent-executor/codex/protocol.d.ts +128 -0
- package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
- package/dist/agent-executor/codex/request-answers.d.ts +101 -0
- package/dist/agent-executor/codex/request-answers.d.ts.map +1 -0
- package/dist/agent-executor/codex/session-controls.d.ts +124 -61
- package/dist/agent-executor/codex/session-controls.d.ts.map +1 -1
- package/dist/agent-executor/codex/session.d.ts +10 -36
- package/dist/agent-executor/codex/session.d.ts.map +1 -1
- package/dist/agent-executor/codex/shared-server.d.ts +31 -0
- package/dist/agent-executor/codex/shared-server.d.ts.map +1 -0
- package/dist/agent-executor/codex/shared-thread.d.ts +46 -0
- package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -0
- package/dist/agent-executor/codex/thread-controls.d.ts +144 -0
- package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -0
- package/dist/agent-executor/codex/thread-open.d.ts +66 -0
- package/dist/agent-executor/codex/thread-open.d.ts.map +1 -0
- package/dist/agent-executor/codex/turn-input.d.ts +47 -0
- package/dist/agent-executor/codex/turn-input.d.ts.map +1 -0
- package/dist/agent-executor/contract.d.ts +77 -0
- package/dist/agent-executor/contract.d.ts.map +1 -1
- package/dist/agent-executor/engine.d.ts +6 -2
- package/dist/agent-executor/engine.d.ts.map +1 -1
- package/dist/agent-executor/executor-contract.d.ts +54 -0
- package/dist/agent-executor/executor-contract.d.ts.map +1 -1
- package/dist/agent-executor/handoff-schemas.d.ts +407 -0
- package/dist/agent-executor/handoff-schemas.d.ts.map +1 -0
- package/dist/agent-executor/handoff.d.ts +12 -0
- package/dist/agent-executor/handoff.d.ts.map +1 -0
- package/dist/agent-executor/hello.d.ts +72 -0
- package/dist/agent-executor/hello.d.ts.map +1 -1
- package/dist/agent-executor/image-input.d.ts +22 -0
- package/dist/agent-executor/image-input.d.ts.map +1 -1
- package/dist/agent-executor/projection.d.ts +2 -2
- package/dist/agent-executor/projection.d.ts.map +1 -1
- package/dist/agent-executor/session-primitives.d.ts +10 -1
- package/dist/agent-executor/session-primitives.d.ts.map +1 -1
- package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
- package/dist/agent-executor/testing/replay-driver.d.ts +41 -0
- package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-gate.d.ts +11 -0
- package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-runner.d.ts +27 -0
- package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-scenarios.d.ts +21 -0
- package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-transcript.d.ts +296 -0
- package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -0
- package/dist/agent-executor/vocabulary.d.ts +135 -0
- package/dist/agent-executor/vocabulary.d.ts.map +1 -1
- package/dist/agent-runtime/branch-observations.d.ts +18 -18
- package/dist/agent-runtime/branch-provider.d.ts +2 -2
- package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
- package/dist/agent-runtime/sql-rows.d.ts +10 -10
- package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
- package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
- package/dist/agent-runtime/terminal-commit.d.ts +10 -10
- package/dist/entrypoints/agent-executor/acp.d.ts +4 -1
- package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/acp.js +847 -214
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts +5 -1
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/claude-sdk.js +713 -205
- package/dist/entrypoints/agent-executor/claude.js +44 -19
- package/dist/entrypoints/agent-executor/codex.d.ts +10 -2
- package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/codex.js +2269 -600
- package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
- package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/testing.js +1002 -2
- package/dist/entrypoints/agent-executor.d.ts +4 -2
- package/dist/entrypoints/agent-executor.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor.js +411 -23
- package/dist/entrypoints/agent-runtime.js +4 -23
- package/dist/entrypoints/tools/mcp.d.ts +1 -0
- package/dist/entrypoints/tools/mcp.d.ts.map +1 -1
- package/dist/entrypoints/tools/mcp.js +1 -1
- package/dist/entrypoints/tools/toolkit.js +1 -1
- package/dist/{index-wv2amqm4.js → index-2s8sy57y.js} +36 -103
- package/dist/{index-afb6z77w.js → index-dbp6xemn.js} +75 -7
- package/dist/{index-bjmj2q1z.js → index-jrn3prgm.js} +1 -1
- package/dist/index-kne9g2c5.js +30 -0
- package/dist/index-p1qmpq0p.js +1300 -0
- package/dist/{index-7jqn3b3g.js → index-v759mzed.js} +152 -2
- package/dist/{index-cbhxhma2.js → index-x5ayy5bn.js} +1 -0
- package/dist/index-y0a4gt1s.js +142 -0
- package/dist/tools/internal/rank-tools.d.ts +10 -0
- package/dist/tools/internal/rank-tools.d.ts.map +1 -0
- package/dist/tools/mcp/handler.d.ts +7 -3
- package/dist/tools/mcp/handler.d.ts.map +1 -1
- package/dist/tools/mcp/lazy-discovery.d.ts +47 -0
- package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -0
- package/dist/tools/mcp/mount.d.ts +7 -0
- package/dist/tools/mcp/mount.d.ts.map +1 -1
- package/dist/tools/mcp/register.d.ts +2 -2
- package/dist/tools/mcp/register.d.ts.map +1 -1
- package/llms/agent-executor-acp.txt +7 -8
- package/llms/agent-executor-claude-sdk.txt +4 -2
- package/llms/agent-executor-codex.txt +8 -4
- package/llms/agent-executor-testing.txt +5 -1
- package/llms/agent-executor.txt +7 -6
- package/llms/stitchkit.txt +74 -74
- package/llms/tools-mcp.txt +3 -2
- package/llms/tools.txt +24 -0
- package/llms/{upgrading-0.128.0-0.129.0.txt → upgrading-0.128.0-0.130.0.txt} +30 -3
- package/llms/upgrading.txt +1 -1
- package/llms-full.txt +159 -97
- package/llms.txt +8 -8
- package/package.json +1 -1
- package/dist/index-y71zn1gw.js +0 -586
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
PlanWindowSchema2,
|
|
5
5
|
engineProfile,
|
|
6
6
|
engineEnvironment2
|
|
7
|
-
} from "../../index-
|
|
7
|
+
} from "../../index-dbp6xemn.js";
|
|
8
8
|
import"../../index-09f7w2qq.js";
|
|
9
9
|
import"../../index-v59pxmf1.js";
|
|
10
10
|
import"../../index-qa2jjb65.js";
|
|
@@ -19,15 +19,15 @@ import {
|
|
|
19
19
|
stopConnection,
|
|
20
20
|
withEphemeralConnection,
|
|
21
21
|
safeJsonValue,
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
22
|
+
invokeSafely,
|
|
23
|
+
emitStartupPhase,
|
|
24
|
+
clampUniqueWindowName,
|
|
25
25
|
holdEngineRequest,
|
|
26
26
|
answerEngineRequest,
|
|
27
27
|
drainEngineRequests,
|
|
28
28
|
endEngineTurn,
|
|
29
29
|
loseEngineTurn
|
|
30
|
-
} from "../../index-
|
|
30
|
+
} from "../../index-2s8sy57y.js";
|
|
31
31
|
import"../../index-673drwkn.js";
|
|
32
32
|
import"../../index-vmbxj75t.js";
|
|
33
33
|
import {
|
|
@@ -35,6 +35,11 @@ import {
|
|
|
35
35
|
JSON_RPC_METHOD_NOT_FOUND2,
|
|
36
36
|
createJsonRpcPeer2
|
|
37
37
|
} from "../../index-1q0n6zek.js";
|
|
38
|
+
import {
|
|
39
|
+
validateImageOptions,
|
|
40
|
+
inlineOrderedParts,
|
|
41
|
+
guardedTurnStarter
|
|
42
|
+
} from "../../index-y0a4gt1s.js";
|
|
38
43
|
import"../../index-pzhqydxb.js";
|
|
39
44
|
import {
|
|
40
45
|
spawnEngineProcess2
|
|
@@ -43,7 +48,7 @@ import"../../index-3fym4j8n.js";
|
|
|
43
48
|
import {
|
|
44
49
|
planLimitsReadFailed2,
|
|
45
50
|
mergeRateLimitEvent2
|
|
46
|
-
} from "../../index-
|
|
51
|
+
} from "../../index-jrn3prgm.js";
|
|
47
52
|
import {
|
|
48
53
|
assertUnixSocketPathLength,
|
|
49
54
|
assertExpectedOwnerUid,
|
|
@@ -54,8 +59,12 @@ import {
|
|
|
54
59
|
} from "../../index-jj9228tt.js";
|
|
55
60
|
import {
|
|
56
61
|
isPositiveSafeInteger,
|
|
57
|
-
assertPositiveSafeInteger
|
|
62
|
+
assertPositiveSafeInteger,
|
|
63
|
+
assertNonNegativeSafeInteger
|
|
58
64
|
} from "../../index-gr0kxymw.js";
|
|
65
|
+
import {
|
|
66
|
+
isRecord
|
|
67
|
+
} from "../../index-ps3djm8d.js";
|
|
59
68
|
import {
|
|
60
69
|
assertTimerMs,
|
|
61
70
|
withSignalDeadline
|
|
@@ -85,6 +94,14 @@ var CodexTurnSchema = z.looseObject({
|
|
|
85
94
|
error: z.looseObject({ message: z.string(), codexErrorInfo: z.json().nullable().optional() }).nullable().optional(),
|
|
86
95
|
items: z.array(z.looseObject({ type: z.string(), clientId: z.string().nullable().optional() })).optional()
|
|
87
96
|
});
|
|
97
|
+
var CodexTokenUsageBreakdownSchema = z.looseObject({
|
|
98
|
+
inputTokens: z.int().nonnegative().optional(),
|
|
99
|
+
outputTokens: z.int().nonnegative().optional(),
|
|
100
|
+
cachedInputTokens: z.int().nonnegative().optional(),
|
|
101
|
+
cacheWriteInputTokens: z.int().nonnegative().optional(),
|
|
102
|
+
reasoningOutputTokens: z.int().nonnegative().optional(),
|
|
103
|
+
totalTokens: z.int().nonnegative().optional()
|
|
104
|
+
});
|
|
88
105
|
var CodexNotificationParams = {
|
|
89
106
|
"item/agentMessage/delta": z.looseObject({ itemId: z.string(), delta: z.string() }),
|
|
90
107
|
"item/reasoning/textDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
|
|
@@ -97,8 +114,13 @@ var CodexNotificationParams = {
|
|
|
97
114
|
last: z.looseObject({
|
|
98
115
|
inputTokens: z.int().nonnegative(),
|
|
99
116
|
outputTokens: z.int().nonnegative(),
|
|
100
|
-
cachedInputTokens: z.int().nonnegative().optional()
|
|
101
|
-
|
|
117
|
+
cachedInputTokens: z.int().nonnegative().optional(),
|
|
118
|
+
cacheWriteInputTokens: z.int().nonnegative().optional(),
|
|
119
|
+
reasoningOutputTokens: z.int().nonnegative().optional(),
|
|
120
|
+
totalTokens: z.int().nonnegative().optional()
|
|
121
|
+
}),
|
|
122
|
+
total: CodexTokenUsageBreakdownSchema.optional(),
|
|
123
|
+
modelContextWindow: z.int().nonnegative().nullable().optional()
|
|
102
124
|
})
|
|
103
125
|
}),
|
|
104
126
|
"serverRequest/resolved": z.looseObject({ requestId: z.union([z.string(), z.int()]) }),
|
|
@@ -110,13 +132,87 @@ var CodexNotificationParams = {
|
|
|
110
132
|
var CodexApprovalParamsSchema = z.looseObject({
|
|
111
133
|
itemId: z.string(),
|
|
112
134
|
command: z.string().nullable().optional(),
|
|
113
|
-
|
|
135
|
+
cwd: z.string().nullable().optional(),
|
|
136
|
+
reason: z.string().nullable().optional(),
|
|
137
|
+
grantRoot: z.string().nullable().optional(),
|
|
138
|
+
kind: z.string().nullable().optional(),
|
|
139
|
+
approvalId: z.string().nullable().optional(),
|
|
140
|
+
commandActions: z.array(z.json()).nullable().optional(),
|
|
141
|
+
availableDecisions: z.array(z.json()).nullable().optional()
|
|
142
|
+
});
|
|
143
|
+
var CodexUserInputOptionSchema = z.looseObject({
|
|
144
|
+
label: z.string(),
|
|
145
|
+
description: z.string()
|
|
146
|
+
});
|
|
147
|
+
var CodexUserInputQuestionSchema = z.looseObject({
|
|
148
|
+
id: z.string(),
|
|
149
|
+
question: z.string(),
|
|
150
|
+
header: z.string(),
|
|
151
|
+
isOther: z.boolean().optional(),
|
|
152
|
+
isSecret: z.boolean().optional(),
|
|
153
|
+
options: z.array(CodexUserInputOptionSchema).nullable().optional()
|
|
114
154
|
});
|
|
115
155
|
var CodexUserInputParamsSchema = z.looseObject({
|
|
116
156
|
itemId: z.string(),
|
|
117
|
-
questions: z.array(
|
|
157
|
+
questions: z.array(CodexUserInputQuestionSchema)
|
|
118
158
|
});
|
|
119
159
|
var CodexUserInputAnswersSchema = z.record(z.string(), z.strictObject({ answers: z.array(z.string()) }));
|
|
160
|
+
var CodexPermissionProfileSchema = z.looseObject({
|
|
161
|
+
fileSystem: z.json().nullable().optional(),
|
|
162
|
+
network: z.json().nullable().optional()
|
|
163
|
+
});
|
|
164
|
+
var CodexPermissionsApprovalParamsSchema = z.looseObject({
|
|
165
|
+
threadId: z.string(),
|
|
166
|
+
turnId: z.string(),
|
|
167
|
+
itemId: z.string(),
|
|
168
|
+
cwd: z.string(),
|
|
169
|
+
permissions: CodexPermissionProfileSchema,
|
|
170
|
+
startedAtMs: z.number().int(),
|
|
171
|
+
reason: z.string().nullable().optional(),
|
|
172
|
+
environmentId: z.string().nullable().optional()
|
|
173
|
+
});
|
|
174
|
+
var CodexMcpElicitationBaseFields = {
|
|
175
|
+
serverName: z.string(),
|
|
176
|
+
threadId: z.string(),
|
|
177
|
+
turnId: z.string().nullable().optional(),
|
|
178
|
+
environmentId: z.string().nullable().optional(),
|
|
179
|
+
message: z.string(),
|
|
180
|
+
_meta: z.json().optional()
|
|
181
|
+
};
|
|
182
|
+
var CodexMcpElicitationFormSchemaSchema = z.looseObject({
|
|
183
|
+
type: z.literal("object"),
|
|
184
|
+
properties: z.record(z.string(), z.json()),
|
|
185
|
+
required: z.array(z.string()).nullable().optional(),
|
|
186
|
+
$schema: z.string().nullable().optional()
|
|
187
|
+
});
|
|
188
|
+
var CodexMcpElicitationParamsSchema = z.discriminatedUnion("mode", [
|
|
189
|
+
z.looseObject({
|
|
190
|
+
...CodexMcpElicitationBaseFields,
|
|
191
|
+
mode: z.literal("form"),
|
|
192
|
+
requestedSchema: CodexMcpElicitationFormSchemaSchema
|
|
193
|
+
}),
|
|
194
|
+
z.looseObject({
|
|
195
|
+
...CodexMcpElicitationBaseFields,
|
|
196
|
+
mode: z.literal("openai/form"),
|
|
197
|
+
requestedSchema: z.json()
|
|
198
|
+
}),
|
|
199
|
+
z.looseObject({
|
|
200
|
+
...CodexMcpElicitationBaseFields,
|
|
201
|
+
mode: z.literal("openaiForm"),
|
|
202
|
+
requestedSchema: z.json()
|
|
203
|
+
}),
|
|
204
|
+
z.looseObject({
|
|
205
|
+
...CodexMcpElicitationBaseFields,
|
|
206
|
+
mode: z.literal("url"),
|
|
207
|
+
elicitationId: z.string(),
|
|
208
|
+
url: z.string()
|
|
209
|
+
})
|
|
210
|
+
]);
|
|
211
|
+
var CodexMcpElicitationAnswerSchema = z.strictObject({
|
|
212
|
+
action: z.enum(["accept", "decline", "cancel"]),
|
|
213
|
+
content: z.json().optional(),
|
|
214
|
+
_meta: z.json().optional()
|
|
215
|
+
});
|
|
120
216
|
var CodexThreadContextSchema = z.object({
|
|
121
217
|
model: z.string().optional(),
|
|
122
218
|
modelProvider: z.string().optional(),
|
|
@@ -124,7 +220,11 @@ var CodexThreadContextSchema = z.object({
|
|
|
124
220
|
approvalPolicy: z.json().optional(),
|
|
125
221
|
sandbox: z.json().optional(),
|
|
126
222
|
cwd: z.string().optional(),
|
|
127
|
-
runtimeWorkspaceRoots: z.array(z.string()).readonly().optional()
|
|
223
|
+
runtimeWorkspaceRoots: z.array(z.string()).readonly().optional(),
|
|
224
|
+
thread: z.json().optional()
|
|
225
|
+
});
|
|
226
|
+
var CodexInitializeResponseSchema = z.looseObject({
|
|
227
|
+
userAgent: z.string().nullable().optional()
|
|
128
228
|
});
|
|
129
229
|
var CodexStartedThreadSchema = CodexThreadContextSchema.extend({
|
|
130
230
|
thread: z.looseObject({ id: z.string().min(1) })
|
|
@@ -139,7 +239,8 @@ function extractCodexThreadContext(parsed) {
|
|
|
139
239
|
...parsed.cwd !== undefined && { cwd: parsed.cwd },
|
|
140
240
|
...parsed.runtimeWorkspaceRoots !== undefined && {
|
|
141
241
|
runtimeWorkspaceRoots: parsed.runtimeWorkspaceRoots
|
|
142
|
-
}
|
|
242
|
+
},
|
|
243
|
+
thread: safeJsonValue(parsed.thread)
|
|
143
244
|
};
|
|
144
245
|
}
|
|
145
246
|
var CodexStartedTurnSchema = z.looseObject({
|
|
@@ -160,7 +261,13 @@ var CodexTurnsPageSchema = z.looseObject({
|
|
|
160
261
|
data: z.array(CodexListedTurnSchema),
|
|
161
262
|
nextCursor: z.string().nullable().optional()
|
|
162
263
|
});
|
|
264
|
+
var CodexThreadRevertResponseSchema = z.looseObject({
|
|
265
|
+
thread: z.looseObject({ id: z.string().min(1) }),
|
|
266
|
+
turnsBackwardsCursor: z.string().nullable().optional(),
|
|
267
|
+
itemsBackwardsCursor: z.string().nullable().optional()
|
|
268
|
+
});
|
|
163
269
|
var CODEX_OPTED_OUT_NOTIFICATIONS = [
|
|
270
|
+
"app/list/updated",
|
|
164
271
|
"item/commandExecution/outputDelta",
|
|
165
272
|
"item/fileChange/outputDelta",
|
|
166
273
|
"item/fileChange/patchUpdated",
|
|
@@ -173,27 +280,61 @@ var CODEX_QUIET_NOTIFICATIONS = new Set([
|
|
|
173
280
|
...CODEX_OPTED_OUT_NOTIFICATIONS,
|
|
174
281
|
"thread/started",
|
|
175
282
|
"thread/status/changed",
|
|
283
|
+
"thread/readState/changed",
|
|
284
|
+
"thread/archived",
|
|
285
|
+
"thread/deleted",
|
|
286
|
+
"thread/unarchived",
|
|
287
|
+
"thread/closed",
|
|
288
|
+
"thread/reverted",
|
|
289
|
+
"thread/name/updated",
|
|
290
|
+
"thread/section/changed",
|
|
291
|
+
"thread/attachment/updated",
|
|
292
|
+
"thread/goal/updated",
|
|
293
|
+
"thread/prediction/updated",
|
|
294
|
+
"thread/goal/cleared",
|
|
295
|
+
"thread/queue/changed",
|
|
296
|
+
"project/changed",
|
|
297
|
+
"thread/project/updated",
|
|
298
|
+
"thread/environment/connected",
|
|
299
|
+
"thread/environment/disconnected",
|
|
300
|
+
"thread/settings/updated",
|
|
301
|
+
"thread/compacted",
|
|
176
302
|
"turn/started",
|
|
177
303
|
"turn/plan/updated",
|
|
304
|
+
"turn/moderationMetadata",
|
|
178
305
|
"item/plan/delta",
|
|
306
|
+
"item/commandExecution/terminalInteraction",
|
|
307
|
+
"item/mcpToolCall/progress",
|
|
308
|
+
"item/autoApprovalReview/started",
|
|
309
|
+
"item/autoApprovalReview/completed",
|
|
310
|
+
"autoApprovalReview/strictReviewRequired",
|
|
179
311
|
"item/reasoning/summaryPartAdded",
|
|
180
312
|
"hook/started",
|
|
181
313
|
"hook/completed",
|
|
182
314
|
"warning",
|
|
315
|
+
"guardianWarning",
|
|
316
|
+
"deprecationNotice",
|
|
317
|
+
"configWarning",
|
|
318
|
+
"windows/worldWritableWarning",
|
|
183
319
|
"account/updated",
|
|
184
|
-
"
|
|
185
|
-
"thread/settings/updated",
|
|
186
|
-
"thread/compacted",
|
|
320
|
+
"account/gatewayOAuth/changed",
|
|
187
321
|
"model/rerouted",
|
|
322
|
+
"model/verification",
|
|
323
|
+
"model/safetyBuffering/updated",
|
|
324
|
+
"modelProvider/authRecoveryStarted",
|
|
325
|
+
"modelProvider/authRecoveryCompleted",
|
|
188
326
|
"error"
|
|
189
327
|
]);
|
|
190
328
|
var CODEX_APPROVAL_REQUESTS = new Set([
|
|
191
329
|
"item/commandExecution/requestApproval",
|
|
192
330
|
"item/fileChange/requestApproval"
|
|
193
331
|
]);
|
|
332
|
+
var CODEX_PERMISSIONS_APPROVAL_REQUEST = "item/permissions/requestApproval";
|
|
194
333
|
var CODEX_INPUT_REQUEST = "item/tool/requestUserInput";
|
|
334
|
+
var CODEX_ELICITATION_REQUEST = "mcpServer/elicitation/request";
|
|
195
335
|
var CODEX_APPROVAL_DECISION = {
|
|
196
336
|
approve: "accept",
|
|
337
|
+
approveForSession: "acceptForSession",
|
|
197
338
|
deny: "decline",
|
|
198
339
|
interrupted: "cancel"
|
|
199
340
|
};
|
|
@@ -837,14 +978,16 @@ function validateCodexTransportAndArgs(config) {
|
|
|
837
978
|
throw new TypeError(`[stitchkit] createCodexDriver: unsupported transport kind ${JSON.stringify(Reflect.get(Object(transport), "kind"))}`);
|
|
838
979
|
}
|
|
839
980
|
async function initializeCodexPeer(peer, version) {
|
|
840
|
-
await peer.request("initialize", {
|
|
981
|
+
const reply = await peer.request("initialize", {
|
|
841
982
|
clientInfo: { name: "stitchkit-agent-executor", version },
|
|
842
983
|
capabilities: {
|
|
843
984
|
experimentalApi: true,
|
|
844
985
|
optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
|
|
845
986
|
}
|
|
846
987
|
}, { timeoutMs: BOOTSTRAP_MS });
|
|
988
|
+
const parsed = CodexInitializeResponseSchema.parse(reply);
|
|
847
989
|
peer.notify("initialized");
|
|
990
|
+
return nonEmptyString(parsed.userAgent);
|
|
848
991
|
}
|
|
849
992
|
function sleepAbortable(ms, signal) {
|
|
850
993
|
if (signal.aborted)
|
|
@@ -904,51 +1047,66 @@ async function dialWithEngineRace(input) {
|
|
|
904
1047
|
}
|
|
905
1048
|
});
|
|
906
1049
|
}
|
|
1050
|
+
async function connectCodexStdio(config, profile, cwd, extraArgs, signal, handlers, onEnd, onStartupPhase) {
|
|
1051
|
+
const env = engineEnvironment2(profile, config.ambient);
|
|
1052
|
+
let endedError;
|
|
1053
|
+
let ready = false;
|
|
1054
|
+
const peer = createJsonRpcPeer2({
|
|
1055
|
+
header: "omitted",
|
|
1056
|
+
requestTimeoutMs: REQUEST_MS,
|
|
1057
|
+
send: (line) => engine.send(line),
|
|
1058
|
+
...handlers
|
|
1059
|
+
});
|
|
1060
|
+
const finishEnd = (error) => {
|
|
1061
|
+
if (endedError !== undefined)
|
|
1062
|
+
return;
|
|
1063
|
+
endedError = error;
|
|
1064
|
+
peer.close(error);
|
|
1065
|
+
if (ready)
|
|
1066
|
+
onEnd(error);
|
|
1067
|
+
};
|
|
1068
|
+
emitStartupPhase(onStartupPhase, "spawning");
|
|
1069
|
+
const engine = spawnEngineProcess2({
|
|
1070
|
+
executable: config.executable,
|
|
1071
|
+
args: [...config.prefix, "app-server", ...extraArgs],
|
|
1072
|
+
cwd,
|
|
1073
|
+
env,
|
|
1074
|
+
signal,
|
|
1075
|
+
...config.maxFrameBytes !== undefined && { maxLineBytes: config.maxFrameBytes }
|
|
1076
|
+
});
|
|
1077
|
+
const reading = (async () => {
|
|
1078
|
+
try {
|
|
1079
|
+
for await (const line of engine.lines)
|
|
1080
|
+
peer.receive(line);
|
|
1081
|
+
finishEnd(new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`));
|
|
1082
|
+
} catch (error) {
|
|
1083
|
+
const failed = error instanceof Error ? error : new Error(String(error));
|
|
1084
|
+
finishEnd(failed);
|
|
1085
|
+
await engine.stop().catch(() => {
|
|
1086
|
+
return;
|
|
1087
|
+
});
|
|
1088
|
+
}
|
|
1089
|
+
})();
|
|
1090
|
+
try {
|
|
1091
|
+
emitStartupPhase(onStartupPhase, "initializing");
|
|
1092
|
+
const userAgent = await initializeCodexPeer(peer, config.version);
|
|
1093
|
+
const providerPid = await engine.pidReady ?? engine.pid;
|
|
1094
|
+
if (endedError !== undefined)
|
|
1095
|
+
throw endedError;
|
|
1096
|
+
ready = true;
|
|
1097
|
+
return { engine, peer, reading, providerPid, userAgent };
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
await stopConnection({ engine, reading }, { error });
|
|
1100
|
+
throw error;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
907
1103
|
async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd = () => {
|
|
908
1104
|
return;
|
|
909
|
-
}) {
|
|
1105
|
+
}, onStartupPhase) {
|
|
910
1106
|
const transport = config.transport ?? { kind: "stdio" };
|
|
911
1107
|
const extraArgs = config.serverArgs ?? [];
|
|
912
1108
|
if (transport.kind === "stdio") {
|
|
913
|
-
|
|
914
|
-
const peer = createJsonRpcPeer2({
|
|
915
|
-
header: "omitted",
|
|
916
|
-
requestTimeoutMs: REQUEST_MS,
|
|
917
|
-
send: (line) => engine.send(line),
|
|
918
|
-
...handlers
|
|
919
|
-
});
|
|
920
|
-
const engine = spawnEngineProcess2({
|
|
921
|
-
executable: config.executable,
|
|
922
|
-
args: [...config.prefix, "app-server", ...extraArgs],
|
|
923
|
-
cwd,
|
|
924
|
-
env,
|
|
925
|
-
signal,
|
|
926
|
-
...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
|
|
927
|
-
});
|
|
928
|
-
const reading = (async () => {
|
|
929
|
-
try {
|
|
930
|
-
for await (const line of engine.lines)
|
|
931
|
-
peer.receive(line);
|
|
932
|
-
const ended = new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`);
|
|
933
|
-
peer.close(ended);
|
|
934
|
-
onEnd(ended);
|
|
935
|
-
} catch (error) {
|
|
936
|
-
const failed = error instanceof Error ? error : new Error(String(error));
|
|
937
|
-
peer.close(failed);
|
|
938
|
-
onEnd(failed);
|
|
939
|
-
await engine.stop().catch(() => {
|
|
940
|
-
return;
|
|
941
|
-
});
|
|
942
|
-
}
|
|
943
|
-
})();
|
|
944
|
-
try {
|
|
945
|
-
await initializeCodexPeer(peer, config.version);
|
|
946
|
-
const providerPid = await engine.pidReady ?? engine.pid;
|
|
947
|
-
return { engine, peer, reading, providerPid };
|
|
948
|
-
} catch (error) {
|
|
949
|
-
await stopConnection({ engine, reading }, { error });
|
|
950
|
-
throw error;
|
|
951
|
-
}
|
|
1109
|
+
return connectCodexStdio(config, profile, cwd, extraArgs, signal, handlers, onEnd, onStartupPhase);
|
|
952
1110
|
}
|
|
953
1111
|
let wsClient;
|
|
954
1112
|
let spawnedEngine;
|
|
@@ -993,6 +1151,7 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
993
1151
|
if (transport.kind === "unix-listen") {
|
|
994
1152
|
assertCodexUnixListenTargetAvailable(transport.socketPath, "createCodexDriver");
|
|
995
1153
|
const env = engineEnvironment2(profile, config.ambient);
|
|
1154
|
+
emitStartupPhase(onStartupPhase, "spawning");
|
|
996
1155
|
spawnedEngine = spawnEngineProcess2({
|
|
997
1156
|
executable: config.executable,
|
|
998
1157
|
args: [
|
|
@@ -1006,13 +1165,13 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1006
1165
|
env,
|
|
1007
1166
|
signal,
|
|
1008
1167
|
stdoutMode: "drain",
|
|
1009
|
-
...config.
|
|
1168
|
+
...config.maxFrameBytes !== undefined && { maxLineBytes: config.maxFrameBytes }
|
|
1010
1169
|
});
|
|
1011
1170
|
try {
|
|
1012
1171
|
wsClient = await dialWithEngineRace({
|
|
1013
1172
|
socketPath: transport.socketPath,
|
|
1014
1173
|
listenTimeoutMs: transport.listenTimeoutMs ?? DEFAULT_LISTEN_TIMEOUT_MS,
|
|
1015
|
-
...config.
|
|
1174
|
+
...config.maxFrameBytes !== undefined && { maxFrameBytes: config.maxFrameBytes },
|
|
1016
1175
|
signal,
|
|
1017
1176
|
engine: spawnedEngine,
|
|
1018
1177
|
onMessage,
|
|
@@ -1033,7 +1192,7 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1033
1192
|
expectedOwnerUid: transport.expectedOwnerUid
|
|
1034
1193
|
},
|
|
1035
1194
|
signal,
|
|
1036
|
-
...config.
|
|
1195
|
+
...config.maxFrameBytes !== undefined && { maxFrameBytes: config.maxFrameBytes },
|
|
1037
1196
|
onMessage,
|
|
1038
1197
|
onClose
|
|
1039
1198
|
});
|
|
@@ -1057,12 +1216,15 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1057
1216
|
try {
|
|
1058
1217
|
if (endedError !== undefined)
|
|
1059
1218
|
throw endedError;
|
|
1060
|
-
|
|
1219
|
+
emitStartupPhase(onStartupPhase, "initializing");
|
|
1220
|
+
const userAgent = await initializeCodexPeer(peer, config.version);
|
|
1061
1221
|
if (endedError !== undefined)
|
|
1062
1222
|
throw endedError;
|
|
1063
1223
|
const providerPid = spawnedEngine !== undefined ? await spawnedEngine.pidReady ?? spawnedEngine.pid : undefined;
|
|
1224
|
+
if (endedError !== undefined)
|
|
1225
|
+
throw endedError;
|
|
1064
1226
|
ready = true;
|
|
1065
|
-
return { engine: compositeEngine, peer, reading, providerPid };
|
|
1227
|
+
return { engine: compositeEngine, peer, reading, providerPid, userAgent };
|
|
1066
1228
|
} catch (error) {
|
|
1067
1229
|
await stopConnection({ engine: compositeEngine, reading }, { error });
|
|
1068
1230
|
throw error;
|
|
@@ -1070,7 +1232,6 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1070
1232
|
}
|
|
1071
1233
|
|
|
1072
1234
|
// src/agent-executor/codex/limits.ts
|
|
1073
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
1074
1235
|
import { z as z2 } from "zod";
|
|
1075
1236
|
var MAX_WINDOW_NAME_CHARS = 256;
|
|
1076
1237
|
var MAX_PLAN_WINDOWS = 32;
|
|
@@ -1088,27 +1249,6 @@ var SnapshotSchema = z2.looseObject({
|
|
|
1088
1249
|
function positiveSafeInt(value) {
|
|
1089
1250
|
return isPositiveSafeInteger(value) ? value : undefined;
|
|
1090
1251
|
}
|
|
1091
|
-
function clampWindowName(prefix, suffix, seenNames, disambiguatorSeed) {
|
|
1092
|
-
const maxPrefix = Math.max(1, MAX_WINDOW_NAME_CHARS - suffix.length);
|
|
1093
|
-
let candidate = prefix.length > maxPrefix ? `${prefix.slice(0, maxPrefix)}${suffix}`.slice(0, MAX_WINDOW_NAME_CHARS) : `${prefix}${suffix}`;
|
|
1094
|
-
if (!seenNames.has(candidate)) {
|
|
1095
|
-
seenNames.add(candidate);
|
|
1096
|
-
return candidate;
|
|
1097
|
-
}
|
|
1098
|
-
const digest = createHash2("sha256").update(disambiguatorSeed).digest("hex").slice(0, 8);
|
|
1099
|
-
const tag = `#${digest}${suffix}`;
|
|
1100
|
-
const room = Math.max(1, MAX_WINDOW_NAME_CHARS - tag.length);
|
|
1101
|
-
candidate = `${prefix.slice(0, room)}${tag}`.slice(0, MAX_WINDOW_NAME_CHARS);
|
|
1102
|
-
let n = 2;
|
|
1103
|
-
while (seenNames.has(candidate)) {
|
|
1104
|
-
const indexedTag = `#${digest}_${n}${suffix}`;
|
|
1105
|
-
const indexedRoom = Math.max(1, MAX_WINDOW_NAME_CHARS - indexedTag.length);
|
|
1106
|
-
candidate = `${prefix.slice(0, indexedRoom)}${indexedTag}`.slice(0, MAX_WINDOW_NAME_CHARS);
|
|
1107
|
-
n += 1;
|
|
1108
|
-
}
|
|
1109
|
-
seenNames.add(candidate);
|
|
1110
|
-
return candidate;
|
|
1111
|
-
}
|
|
1112
1252
|
function clampLabel(value) {
|
|
1113
1253
|
const trimmed = nonEmptyString(value)?.trim();
|
|
1114
1254
|
if (trimmed === undefined)
|
|
@@ -1130,7 +1270,7 @@ function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
|
|
|
1130
1270
|
if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
|
|
1131
1271
|
continue;
|
|
1132
1272
|
const suffix = mins === undefined ? `:${slot}` : duplicateDuration ? `:${mins}m:${slot}` : `:${mins}m`;
|
|
1133
|
-
const name =
|
|
1273
|
+
const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
|
|
1134
1274
|
const resetsAt = window.resetsAt !== undefined && window.resetsAt !== null && window.resetsAt > 0 ? epochSecondsToIso(window.resetsAt) : undefined;
|
|
1135
1275
|
out.push(PlanWindowSchema2.parse({
|
|
1136
1276
|
name,
|
|
@@ -1182,200 +1322,490 @@ function codexPlanWindows(reported) {
|
|
|
1182
1322
|
return windows;
|
|
1183
1323
|
}
|
|
1184
1324
|
|
|
1185
|
-
// src/agent-executor/codex/
|
|
1186
|
-
var
|
|
1187
|
-
var
|
|
1188
|
-
|
|
1189
|
-
"
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
]);
|
|
1194
|
-
var CONTENT_ITEMS = new Set([
|
|
1195
|
-
"agentMessage",
|
|
1196
|
-
"reasoning",
|
|
1197
|
-
"userMessage",
|
|
1198
|
-
"plan",
|
|
1199
|
-
"contextCompaction",
|
|
1200
|
-
"hookPrompt"
|
|
1201
|
-
]);
|
|
1202
|
-
function toolName(item) {
|
|
1203
|
-
const tool = Reflect.get(item, "tool");
|
|
1204
|
-
return item.type === "mcpToolCall" || item.type === "dynamicToolCall" ? nonEmptyString(tool) ?? item.type : item.type;
|
|
1325
|
+
// src/agent-executor/codex/thread-controls.ts
|
|
1326
|
+
var MAX_UINT32 = 4294967295;
|
|
1327
|
+
var MAX_THREAD_LIST_IDS = 100;
|
|
1328
|
+
function assertNonEmptyThreadId(threadId, caller) {
|
|
1329
|
+
if (typeof threadId !== "string" || threadId.trim().length === 0) {
|
|
1330
|
+
throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
|
|
1331
|
+
}
|
|
1332
|
+
return threadId;
|
|
1205
1333
|
}
|
|
1206
|
-
function
|
|
1207
|
-
|
|
1208
|
-
|
|
1334
|
+
function assertRequiredNonEmptyString(value, field, caller) {
|
|
1335
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1336
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1337
|
+
}
|
|
1338
|
+
return value;
|
|
1209
1339
|
}
|
|
1210
|
-
function
|
|
1211
|
-
if (
|
|
1340
|
+
function assertOptionalNonEmptyString(value, field, caller) {
|
|
1341
|
+
if (value === undefined)
|
|
1212
1342
|
return;
|
|
1213
|
-
|
|
1214
|
-
|
|
1343
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1344
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
function assertOptionalNonEmptyNoNulString(value, field, caller) {
|
|
1348
|
+
if (value === undefined)
|
|
1349
|
+
return;
|
|
1350
|
+
if (typeof value !== "string" || value.trim().length === 0 || value.includes("\x00")) {
|
|
1351
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string without NUL bytes`);
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
function assertOptionalLimit(limit, caller) {
|
|
1355
|
+
if (limit === undefined || limit === null)
|
|
1356
|
+
return;
|
|
1357
|
+
assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
|
|
1358
|
+
if (limit > MAX_UINT32) {
|
|
1359
|
+
throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
function assertBoundedThreadIdFilter(ids, field, caller) {
|
|
1363
|
+
if (ids === undefined || ids === null)
|
|
1364
|
+
return ids;
|
|
1365
|
+
if (!Array.isArray(ids)) {
|
|
1366
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be an array of strings`);
|
|
1367
|
+
}
|
|
1368
|
+
if (ids.length > MAX_THREAD_LIST_IDS) {
|
|
1369
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must contain at most ${MAX_THREAD_LIST_IDS} entries`);
|
|
1370
|
+
}
|
|
1371
|
+
for (const id of ids) {
|
|
1372
|
+
if (typeof id !== "string" || id.trim().length === 0) {
|
|
1373
|
+
throw new TypeError(`[stitchkit] ${caller}: every ${field} entry must be a non-empty string`);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
return [...ids];
|
|
1377
|
+
}
|
|
1378
|
+
function validateGitInfoUpdate(gitInfo, caller) {
|
|
1379
|
+
if (gitInfo === undefined)
|
|
1380
|
+
return;
|
|
1381
|
+
if (gitInfo === null)
|
|
1382
|
+
return null;
|
|
1383
|
+
if (typeof gitInfo !== "object" || Array.isArray(gitInfo)) {
|
|
1384
|
+
throw new TypeError(`[stitchkit] ${caller}: gitInfo must be a plain object or null`);
|
|
1385
|
+
}
|
|
1386
|
+
const normalized = {};
|
|
1387
|
+
for (const field of ["branch", "originUrl", "sha"]) {
|
|
1388
|
+
const value = gitInfo[field];
|
|
1389
|
+
if (value === undefined)
|
|
1390
|
+
continue;
|
|
1391
|
+
if (value === null) {
|
|
1392
|
+
normalized[field] = null;
|
|
1393
|
+
continue;
|
|
1394
|
+
}
|
|
1395
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1396
|
+
throw new TypeError(`[stitchkit] ${caller}: gitInfo.${field} must be a non-empty string or null`);
|
|
1397
|
+
}
|
|
1398
|
+
normalized[field] = value;
|
|
1399
|
+
}
|
|
1400
|
+
return normalized;
|
|
1401
|
+
}
|
|
1402
|
+
function normalizeListThreadsCwd(cwd) {
|
|
1403
|
+
if (cwd === undefined || cwd === null || typeof cwd === "string")
|
|
1404
|
+
return cwd;
|
|
1405
|
+
return [...cwd];
|
|
1406
|
+
}
|
|
1407
|
+
function buildListThreadsPayload(params) {
|
|
1408
|
+
const caller = "CodexControlClient.listThreads";
|
|
1409
|
+
assertOptionalLimit(params?.limit, caller);
|
|
1410
|
+
const includedThreadIds = assertBoundedThreadIdFilter(params?.includedThreadIds, "includedThreadIds", caller);
|
|
1411
|
+
const excludedThreadIds = assertBoundedThreadIdFilter(params?.excludedThreadIds, "excludedThreadIds", caller);
|
|
1412
|
+
const cwd = normalizeListThreadsCwd(params?.cwd);
|
|
1413
|
+
return {
|
|
1414
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1415
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
1416
|
+
...params?.sortKey !== undefined && { sortKey: params.sortKey },
|
|
1417
|
+
...params?.sortDirection !== undefined && { sortDirection: params.sortDirection },
|
|
1418
|
+
...params?.modelProviders !== undefined && {
|
|
1419
|
+
modelProviders: params.modelProviders === null ? null : [...params.modelProviders]
|
|
1420
|
+
},
|
|
1421
|
+
...params?.sourceKinds !== undefined && {
|
|
1422
|
+
sourceKinds: params.sourceKinds === null ? null : [...params.sourceKinds]
|
|
1423
|
+
},
|
|
1424
|
+
...params?.archived !== undefined && { archived: params.archived },
|
|
1425
|
+
...cwd !== undefined && { cwd },
|
|
1426
|
+
...params?.searchTerm !== undefined && { searchTerm: params.searchTerm },
|
|
1427
|
+
...params?.sectionId !== undefined && { sectionId: params.sectionId },
|
|
1428
|
+
...includedThreadIds !== undefined && {
|
|
1429
|
+
includedThreadIds: includedThreadIds === null ? null : [...includedThreadIds]
|
|
1430
|
+
},
|
|
1431
|
+
...excludedThreadIds !== undefined && {
|
|
1432
|
+
excludedThreadIds: excludedThreadIds === null ? null : [...excludedThreadIds]
|
|
1433
|
+
},
|
|
1434
|
+
...params?.originators !== undefined && {
|
|
1435
|
+
originators: params.originators === null ? null : [...params.originators]
|
|
1436
|
+
},
|
|
1437
|
+
...params?.currentAccountOnly !== undefined && {
|
|
1438
|
+
currentAccountOnly: params.currentAccountOnly
|
|
1439
|
+
},
|
|
1440
|
+
...params?.useStateDbOnly !== undefined && { useStateDbOnly: params.useStateDbOnly }
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
function createCodexThreadControlMethods(call, options = {}) {
|
|
1444
|
+
return {
|
|
1445
|
+
async revertThread(params) {
|
|
1446
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.revertThread");
|
|
1447
|
+
const beforeTurnId = assertRequiredNonEmptyString(params.beforeTurnId, "beforeTurnId", "CodexControlClient.revertThread");
|
|
1448
|
+
const rawReply = await call("thread/revert", { threadId, beforeTurnId });
|
|
1449
|
+
const parsed = CodexThreadRevertResponseSchema.parse(rawReply);
|
|
1450
|
+
return {
|
|
1451
|
+
thread: safeJsonValue(parsed.thread),
|
|
1452
|
+
turnsBackwardsCursor: parsed.turnsBackwardsCursor ?? null,
|
|
1453
|
+
itemsBackwardsCursor: parsed.itemsBackwardsCursor ?? null
|
|
1454
|
+
};
|
|
1455
|
+
},
|
|
1456
|
+
async injectItems(params) {
|
|
1457
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.injectItems");
|
|
1458
|
+
if (!Array.isArray(params.items)) {
|
|
1459
|
+
throw new TypeError("[stitchkit] CodexControlClient.injectItems: items must be an array");
|
|
1460
|
+
}
|
|
1461
|
+
const items = params.items.map((item) => safeJsonValue(item));
|
|
1462
|
+
return call("thread/inject_items", { threadId, items });
|
|
1463
|
+
},
|
|
1464
|
+
async unsubscribeThread(params) {
|
|
1465
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unsubscribeThread");
|
|
1466
|
+
return call("thread/unsubscribe", { threadId });
|
|
1467
|
+
},
|
|
1468
|
+
async listThreads(params) {
|
|
1469
|
+
return call("thread/list", buildListThreadsPayload(params));
|
|
1470
|
+
},
|
|
1471
|
+
async listLoadedThreads(params) {
|
|
1472
|
+
assertOptionalLimit(params?.limit, "CodexControlClient.listLoadedThreads");
|
|
1473
|
+
return call("thread/loaded/list", {
|
|
1474
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1475
|
+
...params?.limit !== undefined && { limit: params.limit }
|
|
1476
|
+
});
|
|
1477
|
+
},
|
|
1478
|
+
async archiveThread(params) {
|
|
1479
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.archiveThread");
|
|
1480
|
+
return call("thread/archive", { threadId });
|
|
1481
|
+
},
|
|
1482
|
+
async unarchiveThread(params) {
|
|
1483
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unarchiveThread");
|
|
1484
|
+
return call("thread/unarchive", { threadId });
|
|
1485
|
+
},
|
|
1486
|
+
async updateThreadMetadata(params) {
|
|
1487
|
+
const caller = "CodexControlClient.updateThreadMetadata";
|
|
1488
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1489
|
+
const gitInfo = validateGitInfoUpdate(params.gitInfo, caller);
|
|
1490
|
+
return call("thread/metadata/update", {
|
|
1491
|
+
threadId,
|
|
1492
|
+
...gitInfo !== undefined && { gitInfo }
|
|
1493
|
+
});
|
|
1494
|
+
},
|
|
1495
|
+
async setThreadName(params) {
|
|
1496
|
+
const caller = "CodexControlClient.setThreadName";
|
|
1497
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1498
|
+
const name = assertRequiredNonEmptyString(params.name, "name", caller);
|
|
1499
|
+
return call("thread/name/set", { threadId, name });
|
|
1500
|
+
},
|
|
1501
|
+
async interruptTurn(params) {
|
|
1502
|
+
options.ensureAlive?.();
|
|
1503
|
+
const caller = "CodexControlClient.interruptTurn";
|
|
1504
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1505
|
+
const turnId = assertRequiredNonEmptyString(params.turnId, "turnId", caller);
|
|
1506
|
+
options.onBeforeInterruptTurn?.(threadId, turnId);
|
|
1507
|
+
await call("turn/interrupt", { threadId, turnId });
|
|
1508
|
+
},
|
|
1509
|
+
async compactThread(params) {
|
|
1510
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.compactThread");
|
|
1511
|
+
await call("thread/compact/start", { threadId });
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
// src/agent-executor/codex/request-answers.ts
|
|
1517
|
+
function isKnownCodexRequestMethod(method) {
|
|
1518
|
+
return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
|
|
1519
|
+
}
|
|
1520
|
+
function externalCodexTurnIdOf(params) {
|
|
1521
|
+
if (typeof params !== "object" || params === null)
|
|
1522
|
+
return "external";
|
|
1523
|
+
const direct = nonEmptyString(Reflect.get(params, "turnId"));
|
|
1524
|
+
if (direct !== undefined)
|
|
1215
1525
|
return direct;
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1526
|
+
const turn = Reflect.get(params, "turn");
|
|
1527
|
+
if (typeof turn === "object" && turn !== null) {
|
|
1528
|
+
const nested = nonEmptyString(Reflect.get(turn, "id"));
|
|
1529
|
+
if (nested !== undefined)
|
|
1530
|
+
return nested;
|
|
1220
1531
|
}
|
|
1221
|
-
return;
|
|
1532
|
+
return "external";
|
|
1222
1533
|
}
|
|
1223
|
-
function
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
if (
|
|
1230
|
-
|
|
1231
|
-
if (
|
|
1232
|
-
|
|
1233
|
-
|
|
1534
|
+
function parseCodexApprovalRequest(method, params) {
|
|
1535
|
+
const asked = CodexApprovalParamsSchema.parse(params);
|
|
1536
|
+
const callId = nonEmptyString(asked.itemId);
|
|
1537
|
+
const metadata = {};
|
|
1538
|
+
if (typeof asked.command === "string")
|
|
1539
|
+
metadata.command = asked.command;
|
|
1540
|
+
if (typeof asked.cwd === "string")
|
|
1541
|
+
metadata.cwd = asked.cwd;
|
|
1542
|
+
if (typeof asked.reason === "string")
|
|
1543
|
+
metadata.reason = asked.reason;
|
|
1544
|
+
if (typeof asked.grantRoot === "string")
|
|
1545
|
+
metadata.grantRoot = asked.grantRoot;
|
|
1546
|
+
if (typeof asked.kind === "string")
|
|
1547
|
+
metadata.kind = asked.kind;
|
|
1548
|
+
if (typeof asked.approvalId === "string")
|
|
1549
|
+
metadata.approvalId = asked.approvalId;
|
|
1550
|
+
if (asked.commandActions != null)
|
|
1551
|
+
metadata.commandActions = asked.commandActions;
|
|
1552
|
+
if (asked.availableDecisions != null)
|
|
1553
|
+
metadata.availableDecisions = asked.availableDecisions;
|
|
1554
|
+
const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
|
|
1555
|
+
const detail = {
|
|
1556
|
+
method,
|
|
1557
|
+
...typeof asked.kind === "string" && { kind: asked.kind },
|
|
1558
|
+
...Array.isArray(asked.availableDecisions) && {
|
|
1559
|
+
availableDecisions: asked.availableDecisions
|
|
1560
|
+
}
|
|
1561
|
+
};
|
|
1562
|
+
return {
|
|
1563
|
+
detail,
|
|
1564
|
+
deltaFields: {
|
|
1565
|
+
...callId !== undefined && { callId },
|
|
1566
|
+
...typeof asked.command === "string" && { prompt: asked.command },
|
|
1567
|
+
...input !== undefined && { input }
|
|
1568
|
+
}
|
|
1569
|
+
};
|
|
1234
1570
|
}
|
|
1235
|
-
function
|
|
1236
|
-
const
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1571
|
+
function parseCodexInputRequest(params) {
|
|
1572
|
+
const asked = CodexUserInputParamsSchema.parse(params);
|
|
1573
|
+
const callId = nonEmptyString(asked.itemId);
|
|
1574
|
+
const questions = asked.questions.map((question) => ({
|
|
1575
|
+
id: question.id,
|
|
1576
|
+
header: question.header,
|
|
1577
|
+
question: question.question,
|
|
1578
|
+
...question.options !== undefined && {
|
|
1579
|
+
options: question.options === null ? null : question.options.map((option) => ({
|
|
1580
|
+
label: option.label,
|
|
1581
|
+
description: option.description
|
|
1582
|
+
}))
|
|
1583
|
+
},
|
|
1584
|
+
...question.isOther !== undefined && { isOther: question.isOther },
|
|
1585
|
+
...question.isSecret !== undefined && { isSecret: question.isSecret }
|
|
1586
|
+
}));
|
|
1587
|
+
const detail = { method: CODEX_INPUT_REQUEST };
|
|
1588
|
+
return {
|
|
1589
|
+
detail,
|
|
1590
|
+
deltaFields: {
|
|
1591
|
+
...callId !== undefined && { callId },
|
|
1592
|
+
input: safeJsonValue(questions)
|
|
1593
|
+
}
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
function parseCodexPermissionsRequest(params) {
|
|
1597
|
+
const asked = CodexPermissionsApprovalParamsSchema.parse(params);
|
|
1598
|
+
const callId = nonEmptyString(asked.itemId);
|
|
1599
|
+
const permissions = safeJsonValue(asked.permissions);
|
|
1600
|
+
const metadata = {
|
|
1601
|
+
threadId: asked.threadId,
|
|
1602
|
+
turnId: asked.turnId,
|
|
1603
|
+
cwd: asked.cwd,
|
|
1604
|
+
permissions,
|
|
1605
|
+
startedAtMs: asked.startedAtMs
|
|
1606
|
+
};
|
|
1607
|
+
if (typeof asked.reason === "string")
|
|
1608
|
+
metadata.reason = asked.reason;
|
|
1609
|
+
if (typeof asked.environmentId === "string")
|
|
1610
|
+
metadata.environmentId = asked.environmentId;
|
|
1611
|
+
const detail = {
|
|
1612
|
+
method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
|
|
1613
|
+
permissions
|
|
1614
|
+
};
|
|
1615
|
+
return {
|
|
1616
|
+
detail,
|
|
1617
|
+
deltaFields: {
|
|
1618
|
+
...callId !== undefined && { callId },
|
|
1619
|
+
...typeof asked.reason === "string" && { prompt: asked.reason },
|
|
1620
|
+
input: safeJsonValue(metadata)
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
function parseCodexElicitationRequest(params) {
|
|
1625
|
+
const asked = CodexMcpElicitationParamsSchema.parse(params);
|
|
1626
|
+
const toolName = nonEmptyString(asked.serverName);
|
|
1627
|
+
const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
|
|
1628
|
+
const metadata = {
|
|
1629
|
+
serverName: asked.serverName,
|
|
1630
|
+
threadId: asked.threadId,
|
|
1631
|
+
mode: asked.mode,
|
|
1632
|
+
message: asked.message
|
|
1633
|
+
};
|
|
1634
|
+
if (asked.turnId !== undefined)
|
|
1635
|
+
metadata.turnId = asked.turnId;
|
|
1636
|
+
if (asked.environmentId !== undefined)
|
|
1637
|
+
metadata.environmentId = asked.environmentId;
|
|
1638
|
+
if (asked._meta !== undefined)
|
|
1639
|
+
metadata._meta = asked._meta;
|
|
1640
|
+
if (asked.mode === "url") {
|
|
1641
|
+
metadata.elicitationId = asked.elicitationId;
|
|
1642
|
+
metadata.url = asked.url;
|
|
1643
|
+
} else {
|
|
1644
|
+
metadata.requestedSchema = asked.requestedSchema;
|
|
1645
|
+
}
|
|
1646
|
+
const detail = {
|
|
1647
|
+
method: CODEX_ELICITATION_REQUEST,
|
|
1648
|
+
elicitationMode: asked.mode
|
|
1649
|
+
};
|
|
1650
|
+
return {
|
|
1651
|
+
detail,
|
|
1652
|
+
deltaFields: {
|
|
1653
|
+
...callId !== undefined && { callId },
|
|
1654
|
+
...toolName !== undefined && { toolName },
|
|
1655
|
+
prompt: asked.message,
|
|
1656
|
+
input: safeJsonValue(metadata)
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
}
|
|
1660
|
+
function parseCodexServerRequest(method, params) {
|
|
1661
|
+
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
1662
|
+
return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
|
|
1663
|
+
}
|
|
1664
|
+
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
1665
|
+
return { kind: "approval", ...parseCodexPermissionsRequest(params) };
|
|
1666
|
+
}
|
|
1667
|
+
if (method === CODEX_ELICITATION_REQUEST) {
|
|
1668
|
+
return { kind: "input", ...parseCodexElicitationRequest(params) };
|
|
1669
|
+
}
|
|
1670
|
+
return { kind: "input", ...parseCodexInputRequest(params) };
|
|
1671
|
+
}
|
|
1672
|
+
function codexStoppedAnswer(method) {
|
|
1673
|
+
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
1674
|
+
return { decision: CODEX_APPROVAL_DECISION.interrupted };
|
|
1675
|
+
}
|
|
1676
|
+
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
1677
|
+
return { permissions: {} };
|
|
1678
|
+
}
|
|
1679
|
+
if (method === CODEX_ELICITATION_REQUEST) {
|
|
1680
|
+
return { action: "cancel" };
|
|
1681
|
+
}
|
|
1682
|
+
return { answers: {} };
|
|
1683
|
+
}
|
|
1684
|
+
var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
|
|
1685
|
+
function buildCodexRequestAnswer(detail, rawReply) {
|
|
1686
|
+
const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
|
|
1687
|
+
if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
|
|
1688
|
+
if (reply.kind === "input") {
|
|
1689
|
+
throw new TypeError("A Codex approval is approved or denied, not answered with input");
|
|
1690
|
+
}
|
|
1691
|
+
if (reply.kind === "approve" && reply.updatedInput !== undefined) {
|
|
1692
|
+
throw new TypeError("Codex approval requests do not support updatedInput");
|
|
1693
|
+
}
|
|
1694
|
+
const decision = reply.kind === "approve" ? reply.scope === "session" ? CODEX_APPROVAL_DECISION.approveForSession : CODEX_APPROVAL_DECISION.approve : reply.interrupt === true ? CODEX_APPROVAL_DECISION.interrupted : CODEX_APPROVAL_DECISION.deny;
|
|
1695
|
+
if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
|
|
1696
|
+
throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
|
|
1697
|
+
}
|
|
1698
|
+
if (detail.availableDecisions !== undefined) {
|
|
1699
|
+
const allowed = detail.availableDecisions.some((entry) => entry === decision);
|
|
1700
|
+
if (!allowed) {
|
|
1701
|
+
throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
return { decision };
|
|
1705
|
+
}
|
|
1706
|
+
if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
1707
|
+
if (reply.kind === "input") {
|
|
1708
|
+
throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
|
|
1709
|
+
}
|
|
1710
|
+
if (reply.kind === "approve") {
|
|
1711
|
+
if (reply.updatedInput !== undefined) {
|
|
1712
|
+
throw new TypeError("Codex permissions approval requests do not support updatedInput");
|
|
1713
|
+
}
|
|
1240
1714
|
return {
|
|
1241
|
-
|
|
1242
|
-
|
|
1715
|
+
permissions: detail.permissions ?? {},
|
|
1716
|
+
scope: reply.scope === "session" ? "session" : "turn"
|
|
1243
1717
|
};
|
|
1244
1718
|
}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1719
|
+
if (reply.interrupt === true) {
|
|
1720
|
+
throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
|
|
1721
|
+
}
|
|
1722
|
+
return { permissions: {} };
|
|
1723
|
+
}
|
|
1724
|
+
if (detail.method === CODEX_ELICITATION_REQUEST) {
|
|
1725
|
+
if (reply.kind === "approve") {
|
|
1726
|
+
throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
|
|
1727
|
+
}
|
|
1728
|
+
if (reply.kind === "deny") {
|
|
1248
1729
|
return {
|
|
1249
|
-
|
|
1250
|
-
deltas: [
|
|
1251
|
-
{ type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
|
|
1252
|
-
]
|
|
1730
|
+
action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
|
|
1253
1731
|
};
|
|
1254
1732
|
}
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
|
|
1313
|
-
const deltas = [];
|
|
1314
|
-
if (outcome === "failed") {
|
|
1315
|
-
deltas.push({
|
|
1316
|
-
type: "error",
|
|
1317
|
-
...base,
|
|
1318
|
-
itemId: "failure",
|
|
1319
|
-
raw: raw(method),
|
|
1320
|
-
kind: failureKind(turn.error?.codexErrorInfo),
|
|
1321
|
-
message: turn.error?.message || `Codex ended the turn ${turn.status}`
|
|
1322
|
-
});
|
|
1323
|
-
}
|
|
1324
|
-
deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
|
|
1325
|
-
return { kind: "end", deltas, outcome };
|
|
1326
|
-
}
|
|
1327
|
-
case "thread/tokenUsage/updated": {
|
|
1328
|
-
const { last } = CodexNotificationParams[method].parse(params).tokenUsage;
|
|
1329
|
-
return {
|
|
1330
|
-
kind: "deltas",
|
|
1331
|
-
deltas: [
|
|
1332
|
-
{
|
|
1333
|
-
type: "usage",
|
|
1334
|
-
...base,
|
|
1335
|
-
itemId: "usage",
|
|
1336
|
-
raw: raw(method),
|
|
1337
|
-
inputTokens: last.inputTokens,
|
|
1338
|
-
outputTokens: last.outputTokens,
|
|
1339
|
-
...last.cachedInputTokens !== undefined && {
|
|
1340
|
-
cachedInputTokens: last.cachedInputTokens
|
|
1341
|
-
}
|
|
1342
|
-
}
|
|
1343
|
-
]
|
|
1344
|
-
};
|
|
1733
|
+
const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
|
|
1734
|
+
return {
|
|
1735
|
+
action: parsed.action,
|
|
1736
|
+
...parsed.content !== undefined && { content: parsed.content },
|
|
1737
|
+
...parsed._meta !== undefined && { _meta: parsed._meta }
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
if (reply.kind !== "input") {
|
|
1741
|
+
throw new TypeError("A Codex input request is answered with input");
|
|
1742
|
+
}
|
|
1743
|
+
return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
|
|
1744
|
+
}
|
|
1745
|
+
function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
|
|
1746
|
+
const waiting = turn.pending.get(interactionId);
|
|
1747
|
+
if (waiting === undefined) {
|
|
1748
|
+
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
1749
|
+
}
|
|
1750
|
+
const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
|
|
1751
|
+
answerEngineRequest(turn, interactionId, answer);
|
|
1752
|
+
}
|
|
1753
|
+
function answerCodexSessionRequest(input) {
|
|
1754
|
+
if (input.turn?.pending.has(input.interactionId)) {
|
|
1755
|
+
answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
|
|
1756
|
+
return;
|
|
1757
|
+
}
|
|
1758
|
+
const external = input.externalPending.get(input.interactionId);
|
|
1759
|
+
if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
|
|
1760
|
+
throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
|
|
1761
|
+
}
|
|
1762
|
+
const answer = buildCodexRequestAnswer(external.detail, input.reply);
|
|
1763
|
+
input.externalPending.delete(input.interactionId);
|
|
1764
|
+
external.resolve(answer);
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
// src/agent-executor/codex/turn-input.ts
|
|
1768
|
+
import { isAbsolute } from "node:path";
|
|
1769
|
+
import { z as z3 } from "zod";
|
|
1770
|
+
var NonEmptyNoNulStringSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00"), {
|
|
1771
|
+
message: "must be a non-empty string without NUL bytes"
|
|
1772
|
+
});
|
|
1773
|
+
var AbsolutePathNoNulSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00") && isAbsolute(value), {
|
|
1774
|
+
message: "must be an absolute path without NUL bytes"
|
|
1775
|
+
});
|
|
1776
|
+
var CodexSkillInputSchema = z3.strictObject({
|
|
1777
|
+
type: z3.literal("skill"),
|
|
1778
|
+
name: NonEmptyNoNulStringSchema,
|
|
1779
|
+
path: NonEmptyNoNulStringSchema
|
|
1780
|
+
});
|
|
1781
|
+
var CodexLocalImageInputSchema = z3.strictObject({
|
|
1782
|
+
type: z3.literal("localImage"),
|
|
1783
|
+
path: AbsolutePathNoNulSchema
|
|
1784
|
+
});
|
|
1785
|
+
function validateCodexExtraInput(part) {
|
|
1786
|
+
if (part.type === "skill") {
|
|
1787
|
+
const parsed = CodexSkillInputSchema.safeParse(part);
|
|
1788
|
+
if (!parsed.success) {
|
|
1789
|
+
throw new TypeError("Codex skill input name and path must be non-empty strings without NUL bytes");
|
|
1345
1790
|
}
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
const parsed = CodexNotificationParams[method].parse(params);
|
|
1353
|
-
return {
|
|
1354
|
-
kind: "limits",
|
|
1355
|
-
rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
|
|
1356
|
-
rateLimits: parsed.rateLimits,
|
|
1357
|
-
rateLimitsByLimitId: parsed.rateLimitsByLimitId
|
|
1358
|
-
} : parsed.rateLimits
|
|
1359
|
-
};
|
|
1791
|
+
return { type: "skill", name: parsed.data.name, path: parsed.data.path };
|
|
1792
|
+
}
|
|
1793
|
+
if (part.type === "localImage") {
|
|
1794
|
+
const parsed = CodexLocalImageInputSchema.safeParse(part);
|
|
1795
|
+
if (!parsed.success) {
|
|
1796
|
+
throw new TypeError("Codex localImage input path must be an absolute path without NUL bytes");
|
|
1360
1797
|
}
|
|
1361
|
-
|
|
1362
|
-
if (CODEX_QUIET_NOTIFICATIONS.has(method))
|
|
1363
|
-
return { kind: "ignore", reason: method };
|
|
1364
|
-
return {
|
|
1365
|
-
kind: "unhandled",
|
|
1366
|
-
delta: {
|
|
1367
|
-
type: "error",
|
|
1368
|
-
...base,
|
|
1369
|
-
itemId: `unhandled:${method}`,
|
|
1370
|
-
raw: raw(method),
|
|
1371
|
-
kind: "unhandled",
|
|
1372
|
-
message: `Codex notification ${method} is not known to this driver`
|
|
1373
|
-
}
|
|
1374
|
-
};
|
|
1798
|
+
return { type: "localImage", path: parsed.data.path };
|
|
1375
1799
|
}
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
function inlineCodexParts(parts, options) {
|
|
1803
|
+
return inlineOrderedParts(parts, {
|
|
1804
|
+
...options,
|
|
1805
|
+
acceptedDescription: "text, images, local images, and skills",
|
|
1806
|
+
validateExtra: validateCodexExtraInput
|
|
1807
|
+
});
|
|
1376
1808
|
}
|
|
1377
|
-
|
|
1378
|
-
// src/agent-executor/codex/session-controls.ts
|
|
1379
1809
|
function codexTurnInput(parts) {
|
|
1380
1810
|
if (parts.every((part) => part.type === "text")) {
|
|
1381
1811
|
return [
|
|
@@ -1387,12 +1817,32 @@ function codexTurnInput(parts) {
|
|
|
1387
1817
|
for (const part of parts) {
|
|
1388
1818
|
if (part.type === "text") {
|
|
1389
1819
|
out.push({ type: "text", text: part.text, text_elements: [] });
|
|
1820
|
+
} else if (part.type === "skill") {
|
|
1821
|
+
out.push({ type: "skill", name: part.name, path: part.path });
|
|
1822
|
+
} else if (part.type === "localImage") {
|
|
1823
|
+
out.push({ type: "localImage", path: part.path });
|
|
1390
1824
|
} else {
|
|
1391
1825
|
out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
|
|
1392
1826
|
}
|
|
1393
1827
|
}
|
|
1394
1828
|
return out;
|
|
1395
1829
|
}
|
|
1830
|
+
async function sendCodexTurnSteer(peer, params) {
|
|
1831
|
+
const steered = CodexTurnSteerResponseSchema.parse(await peer.request("turn/steer", {
|
|
1832
|
+
threadId: params.threadId,
|
|
1833
|
+
expectedTurnId: params.expectedTurnId,
|
|
1834
|
+
input: codexTurnInput(params.parts),
|
|
1835
|
+
...params.clientId !== undefined && { clientUserMessageId: params.clientId }
|
|
1836
|
+
}));
|
|
1837
|
+
return { turnId: steered.turnId };
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
// src/agent-executor/codex/session-controls.ts
|
|
1841
|
+
function validateCodexForkBounds(options, caller) {
|
|
1842
|
+
if (options.beforeTurnId !== undefined && options.lastTurnId !== undefined) {
|
|
1843
|
+
throw new TypeError(`[stitchkit] ${caller}: beforeTurnId and lastTurnId are mutually exclusive`);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1396
1846
|
function validateCodexPolicyOverrides(overrides, caller) {
|
|
1397
1847
|
if (overrides.runtimeWorkspaceRoots !== undefined) {
|
|
1398
1848
|
if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
|
|
@@ -1437,6 +1887,7 @@ function buildCodexThreadPolicyParams(base, overrides) {
|
|
|
1437
1887
|
return params;
|
|
1438
1888
|
}
|
|
1439
1889
|
function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
|
|
1890
|
+
assertOptionalNonEmptyNoNulString(turnInput.cwd, "cwd", "CodexSession.startTurn");
|
|
1440
1891
|
if (turnInput.modelProvider !== undefined) {
|
|
1441
1892
|
if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
|
|
1442
1893
|
throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
|
|
@@ -1462,6 +1913,8 @@ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvid
|
|
|
1462
1913
|
input: codexTurnInput(parts),
|
|
1463
1914
|
clientUserMessageId: turnInput.clientId
|
|
1464
1915
|
};
|
|
1916
|
+
if (turnInput.cwd !== undefined)
|
|
1917
|
+
params.cwd = turnInput.cwd;
|
|
1465
1918
|
if (turnInput.model !== undefined)
|
|
1466
1919
|
params.model = turnInput.model;
|
|
1467
1920
|
if (turnInput.reasoningEffort !== undefined)
|
|
@@ -1480,85 +1933,69 @@ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvid
|
|
|
1480
1933
|
}
|
|
1481
1934
|
return params;
|
|
1482
1935
|
}
|
|
1483
|
-
function createCodexControlClient(input) {
|
|
1484
|
-
const call = async (method, params) => {
|
|
1485
|
-
input.ensureAlive();
|
|
1486
|
-
return input.peer.request(method, params);
|
|
1487
|
-
};
|
|
1488
|
-
return {
|
|
1489
|
-
readConfig(params) {
|
|
1490
|
-
return call("config/read", {
|
|
1491
|
-
...params?.cwd !== undefined && { cwd: params.cwd },
|
|
1492
|
-
...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
|
|
1493
|
-
});
|
|
1494
|
-
},
|
|
1495
|
-
listMcpServerStatus(params) {
|
|
1496
|
-
return call("mcpServerStatus/list", {
|
|
1497
|
-
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1498
|
-
...params?.limit !== undefined && { limit: params.limit },
|
|
1499
|
-
...params?.threadId !== undefined && { threadId: params.threadId },
|
|
1500
|
-
...params?.serverName !== undefined && { serverName: params.serverName },
|
|
1501
|
-
...params?.detail !== undefined && { detail: params.detail }
|
|
1502
|
-
});
|
|
1503
|
-
},
|
|
1504
|
-
listSkills(params) {
|
|
1505
|
-
return call("skills/list", {
|
|
1506
|
-
...params?.cwds !== undefined && { cwds: [...params.cwds] },
|
|
1507
|
-
...params?.forceReload !== undefined && { forceReload: params.forceReload }
|
|
1508
|
-
});
|
|
1509
|
-
},
|
|
1510
|
-
listModels(params) {
|
|
1511
|
-
return call("model/list", {
|
|
1512
|
-
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1513
|
-
...params?.limit !== undefined && { limit: params.limit },
|
|
1514
|
-
...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
|
|
1515
|
-
...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
|
|
1516
|
-
});
|
|
1517
|
-
},
|
|
1518
|
-
readAccount(params) {
|
|
1519
|
-
return call("account/read", {
|
|
1520
|
-
...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
|
|
1521
|
-
});
|
|
1522
|
-
},
|
|
1523
|
-
readRateLimits() {
|
|
1524
|
-
return call("account/rateLimits/read");
|
|
1525
|
-
}
|
|
1526
|
-
};
|
|
1527
|
-
}
|
|
1528
1936
|
function createCodexSessionMutators(input) {
|
|
1529
1937
|
return {
|
|
1530
1938
|
async steerTurn(steerInput) {
|
|
1531
1939
|
input.ensureAlive();
|
|
1532
|
-
const
|
|
1533
|
-
const
|
|
1534
|
-
|
|
1535
|
-
|
|
1940
|
+
const caller = "CodexSession.steerTurn";
|
|
1941
|
+
const targetThreadId = steerInput.threadId === undefined ? input.threadId : assertNonEmptyThreadId(steerInput.threadId, caller);
|
|
1942
|
+
assertOptionalNonEmptyString(steerInput.clientId, "clientId", caller);
|
|
1943
|
+
assertOptionalNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
|
|
1944
|
+
if (targetThreadId !== input.threadId) {
|
|
1945
|
+
const expectedTurnId = assertRequiredNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
|
|
1946
|
+
const parts = await inlineCodexParts(steerInput.input, {
|
|
1947
|
+
...input.imageOptions,
|
|
1948
|
+
driverLabel: "The Codex driver",
|
|
1949
|
+
signal: input.signal
|
|
1950
|
+
});
|
|
1951
|
+
input.ensureAlive();
|
|
1952
|
+
return sendCodexTurnSteer(input.peer, {
|
|
1953
|
+
threadId: targetThreadId,
|
|
1954
|
+
expectedTurnId,
|
|
1955
|
+
parts,
|
|
1956
|
+
...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
|
|
1957
|
+
});
|
|
1536
1958
|
}
|
|
1537
|
-
|
|
1538
|
-
|
|
1959
|
+
const active = input.getActiveTurn();
|
|
1960
|
+
let expectedTurnId;
|
|
1961
|
+
if (active !== undefined) {
|
|
1962
|
+
if (active.codexTurnId === undefined) {
|
|
1963
|
+
throw new Error("Cannot steer turn: no Codex turn is currently running");
|
|
1964
|
+
}
|
|
1965
|
+
if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== active.codexTurnId) {
|
|
1966
|
+
throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${active.codexTurnId}`);
|
|
1967
|
+
}
|
|
1968
|
+
expectedTurnId = active.codexTurnId;
|
|
1969
|
+
} else {
|
|
1970
|
+
if (steerInput.expectedTurnId === undefined) {
|
|
1971
|
+
throw new Error("Cannot steer turn: no Codex turn is currently running");
|
|
1972
|
+
}
|
|
1973
|
+
expectedTurnId = steerInput.expectedTurnId;
|
|
1539
1974
|
}
|
|
1540
|
-
const parts = await
|
|
1975
|
+
const parts = await inlineCodexParts(steerInput.input, {
|
|
1541
1976
|
...input.imageOptions,
|
|
1542
1977
|
driverLabel: "The Codex driver",
|
|
1543
1978
|
signal: input.signal
|
|
1544
1979
|
});
|
|
1545
1980
|
input.ensureAlive();
|
|
1546
1981
|
const afterAwait = input.getActiveTurn();
|
|
1547
|
-
if (
|
|
1548
|
-
|
|
1982
|
+
if (active !== undefined) {
|
|
1983
|
+
if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
|
|
1984
|
+
throw new Error("Cannot steer turn: the active Codex turn ended before steering was sent");
|
|
1985
|
+
}
|
|
1986
|
+
} else if (afterAwait !== undefined && afterAwait.codexTurnId !== expectedTurnId) {
|
|
1987
|
+
throw new TypeError(`Expected active Codex turn ${expectedTurnId}, but current turn is ${afterAwait.codexTurnId ?? "starting"}`);
|
|
1549
1988
|
}
|
|
1550
|
-
|
|
1989
|
+
return sendCodexTurnSteer(input.peer, {
|
|
1551
1990
|
threadId: input.threadId,
|
|
1552
1991
|
expectedTurnId,
|
|
1553
|
-
|
|
1554
|
-
...steerInput.clientId !== undefined && {
|
|
1555
|
-
|
|
1556
|
-
}
|
|
1557
|
-
}));
|
|
1558
|
-
return { turnId: steered.turnId };
|
|
1992
|
+
parts,
|
|
1993
|
+
...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
|
|
1994
|
+
});
|
|
1559
1995
|
},
|
|
1560
1996
|
async forkThread(options = {}) {
|
|
1561
1997
|
input.ensureAlive();
|
|
1998
|
+
validateCodexForkBounds(options, "CodexSession.forkThread");
|
|
1562
1999
|
const policyParams = buildCodexThreadPolicyParams({}, options);
|
|
1563
2000
|
const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
|
|
1564
2001
|
threadId: input.threadId,
|
|
@@ -1566,162 +2003,57 @@ function createCodexSessionMutators(input) {
|
|
|
1566
2003
|
...options.cwd !== undefined && { cwd: options.cwd },
|
|
1567
2004
|
...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
|
|
1568
2005
|
...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
|
|
1569
|
-
...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns }
|
|
2006
|
+
...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns },
|
|
2007
|
+
...options.deferGoalContinuation !== undefined && {
|
|
2008
|
+
deferGoalContinuation: options.deferGoalContinuation
|
|
2009
|
+
}
|
|
1570
2010
|
}));
|
|
1571
2011
|
return {
|
|
1572
2012
|
nativeThreadId: forked.thread.id,
|
|
1573
2013
|
threadContext: extractCodexThreadContext(forked)
|
|
1574
2014
|
};
|
|
1575
|
-
},
|
|
1576
|
-
async compactThread() {
|
|
1577
|
-
input.ensureAlive();
|
|
1578
|
-
await input.peer.request("thread/compact/start", { threadId: input.threadId });
|
|
1579
2015
|
}
|
|
1580
2016
|
};
|
|
1581
2017
|
}
|
|
1582
2018
|
|
|
1583
|
-
// src/agent-executor/codex/
|
|
1584
|
-
function
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
...typeof asked.command === "string" && { prompt: asked.command }
|
|
1590
|
-
};
|
|
1591
|
-
}
|
|
1592
|
-
function inputDetail(params) {
|
|
1593
|
-
const asked = CodexUserInputParamsSchema.parse(params);
|
|
1594
|
-
const callId = nonEmptyString(asked.itemId);
|
|
1595
|
-
return {
|
|
1596
|
-
...callId !== undefined && { callId },
|
|
1597
|
-
input: asked.questions.map((question) => ({
|
|
1598
|
-
id: question.id,
|
|
1599
|
-
question: question.question
|
|
1600
|
-
}))
|
|
1601
|
-
};
|
|
1602
|
-
}
|
|
1603
|
-
function codexStoppedAnswer(method) {
|
|
1604
|
-
return CODEX_APPROVAL_REQUESTS.has(method) ? { decision: CODEX_APPROVAL_DECISION.interrupted } : { answers: {} };
|
|
2019
|
+
// src/agent-executor/codex/thread-open.ts
|
|
2020
|
+
function interruptLocalCodexTurn(turn, turnId) {
|
|
2021
|
+
if (turn === undefined || turn.codexTurnId !== turnId)
|
|
2022
|
+
return;
|
|
2023
|
+
turn.state.interruptRequested = true;
|
|
2024
|
+
drainEngineRequests(turn, codexStopped);
|
|
1605
2025
|
}
|
|
1606
|
-
|
|
1607
|
-
|
|
2026
|
+
function buildCodexResumeThreadParams(params) {
|
|
2027
|
+
const caller = "CodexControlClient.resumeThread";
|
|
2028
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2029
|
+
assertOptionalNonEmptyNoNulString(params.cwd, "cwd", caller);
|
|
2030
|
+
if (params.excludeTurns !== undefined && typeof params.excludeTurns !== "boolean") {
|
|
2031
|
+
throw new TypeError(`[stitchkit] ${caller}: excludeTurns must be a boolean`);
|
|
2032
|
+
}
|
|
2033
|
+
const policyParams = buildCodexThreadPolicyParams({}, params);
|
|
1608
2034
|
return {
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: "between-turns", interruptRequested: false });
|
|
1614
|
-
} catch (error) {
|
|
1615
|
-
if (turn !== undefined) {
|
|
1616
|
-
offerTurnDelta(turn.channel, {
|
|
1617
|
-
type: "error",
|
|
1618
|
-
turnId: turn.state.turnId,
|
|
1619
|
-
itemId: `unhandled:${method}`,
|
|
1620
|
-
raw: { source: "codex", type: method },
|
|
1621
|
-
kind: "unhandled",
|
|
1622
|
-
message: `Codex notification ${method} did not match schema: ${error instanceof Error ? error.message : String(error)}`
|
|
1623
|
-
});
|
|
1624
|
-
}
|
|
1625
|
-
return;
|
|
1626
|
-
}
|
|
1627
|
-
switch (verdict.kind) {
|
|
1628
|
-
case "limits":
|
|
1629
|
-
try {
|
|
1630
|
-
state.limits.set(state.profileId, mergeRateLimitEvent2({
|
|
1631
|
-
previous: state.limits.get(state.profileId),
|
|
1632
|
-
windows: codexPlanWindows(verdict.rateLimits),
|
|
1633
|
-
now: new Date
|
|
1634
|
-
}));
|
|
1635
|
-
} catch (error) {
|
|
1636
|
-
if (turn !== undefined) {
|
|
1637
|
-
offerTurnDelta(turn.channel, {
|
|
1638
|
-
type: "error",
|
|
1639
|
-
turnId: turn.state.turnId,
|
|
1640
|
-
itemId: `unhandled:${method}`,
|
|
1641
|
-
raw: { source: "codex", type: method },
|
|
1642
|
-
kind: "unhandled",
|
|
1643
|
-
message: `Codex rate-limit update could not be merged: ${error instanceof Error ? error.message : String(error)}`
|
|
1644
|
-
});
|
|
1645
|
-
}
|
|
1646
|
-
}
|
|
1647
|
-
return;
|
|
1648
|
-
case "resolved":
|
|
1649
|
-
if (turn?.pending.delete(verdict.requestId)) {
|
|
1650
|
-
offerTurnDelta(turn.channel, {
|
|
1651
|
-
type: "request-resolved",
|
|
1652
|
-
turnId: turn.state.turnId,
|
|
1653
|
-
itemId: `resolved:${verdict.requestId}`,
|
|
1654
|
-
raw: { source: "codex", type: "serverRequest/resolved" },
|
|
1655
|
-
interactionId: verdict.requestId
|
|
1656
|
-
});
|
|
1657
|
-
}
|
|
1658
|
-
return;
|
|
1659
|
-
case "deltas":
|
|
1660
|
-
case "unhandled":
|
|
1661
|
-
if (turn !== undefined)
|
|
1662
|
-
for (const delta of verdict.kind === "deltas" ? verdict.deltas : [verdict.delta])
|
|
1663
|
-
offerTurnDelta(turn.channel, delta);
|
|
1664
|
-
return;
|
|
1665
|
-
case "end":
|
|
1666
|
-
endEngineTurn(turn, codexStopped, verdict.deltas);
|
|
1667
|
-
state.clearTurn();
|
|
1668
|
-
return;
|
|
1669
|
-
case "ignore":
|
|
1670
|
-
return;
|
|
1671
|
-
}
|
|
1672
|
-
},
|
|
1673
|
-
onRequest(method, params, id) {
|
|
1674
|
-
const turn = state.getTurn();
|
|
1675
|
-
const known = CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_INPUT_REQUEST;
|
|
1676
|
-
if (turn === undefined || !known) {
|
|
1677
|
-
if (turn !== undefined) {
|
|
1678
|
-
offerTurnDelta(turn.channel, {
|
|
1679
|
-
type: "error",
|
|
1680
|
-
turnId: turn.state.turnId,
|
|
1681
|
-
itemId: `unhandled-request:${id}`,
|
|
1682
|
-
raw: { source: "codex", type: method },
|
|
1683
|
-
kind: "unhandled",
|
|
1684
|
-
message: `Codex request ${method} is not known to this driver; refused`
|
|
1685
|
-
});
|
|
1686
|
-
}
|
|
1687
|
-
throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
|
|
1688
|
-
}
|
|
1689
|
-
const interactionId = String(id);
|
|
1690
|
-
const approval = CODEX_APPROVAL_REQUESTS.has(method);
|
|
1691
|
-
return new Promise((resolve) => {
|
|
1692
|
-
holdEngineRequest(turn, {
|
|
1693
|
-
interactionId,
|
|
1694
|
-
detail: { method },
|
|
1695
|
-
answeredBy: { source: "codex", type: method },
|
|
1696
|
-
delta: () => ({
|
|
1697
|
-
type: "request",
|
|
1698
|
-
turnId: turn.state.turnId,
|
|
1699
|
-
itemId: `request:${interactionId}`,
|
|
1700
|
-
raw: { source: "codex", type: method },
|
|
1701
|
-
interactionId,
|
|
1702
|
-
kind: approval ? "approval" : "input",
|
|
1703
|
-
...approval ? approvalDetail(params) : inputDetail(params)
|
|
1704
|
-
}),
|
|
1705
|
-
refusal: codexStoppedAnswer(method),
|
|
1706
|
-
resolve
|
|
1707
|
-
});
|
|
1708
|
-
});
|
|
1709
|
-
}
|
|
2035
|
+
threadId,
|
|
2036
|
+
excludeTurns: params.excludeTurns ?? true,
|
|
2037
|
+
...policyParams,
|
|
2038
|
+
...params.cwd !== undefined && { cwd: params.cwd }
|
|
1710
2039
|
};
|
|
1711
2040
|
}
|
|
1712
2041
|
function createCodexStartTurn(input) {
|
|
1713
|
-
return
|
|
1714
|
-
driverLabel: "The Codex driver",
|
|
2042
|
+
return guardedTurnStarter({
|
|
1715
2043
|
busyMessage: "A turn is already running in this Codex thread",
|
|
1716
|
-
|
|
1717
|
-
signal: input.signal,
|
|
1718
|
-
check(turnInput) {
|
|
2044
|
+
check: (turnInput) => {
|
|
1719
2045
|
input.ensureAlive();
|
|
1720
|
-
if (input.getTurn() !== undefined)
|
|
2046
|
+
if (input.getTurn() !== undefined) {
|
|
1721
2047
|
throw new Error("A turn is already running in this Codex thread");
|
|
2048
|
+
}
|
|
1722
2049
|
validateCodexTurnStartOverrides(turnInput, input.activeModelProvider);
|
|
1723
2050
|
},
|
|
1724
|
-
|
|
2051
|
+
inline: (turnInput) => inlineCodexParts(turnInput.input, {
|
|
2052
|
+
...input.config,
|
|
2053
|
+
driverLabel: "The Codex driver",
|
|
2054
|
+
signal: input.signal
|
|
2055
|
+
}),
|
|
2056
|
+
dispatch: async (turnInput, parts) => {
|
|
1725
2057
|
const turnParams = buildCodexTurnStartParams(input.threadId, turnInput, parts, input.activeModelProvider);
|
|
1726
2058
|
const turn = {
|
|
1727
2059
|
state: { turnId: turnInput.turnId, interruptRequested: false },
|
|
@@ -1729,84 +2061,888 @@ function createCodexStartTurn(input) {
|
|
|
1729
2061
|
pending: new Map
|
|
1730
2062
|
};
|
|
1731
2063
|
input.setTurn(turn);
|
|
2064
|
+
let nativeTurnId;
|
|
1732
2065
|
try {
|
|
1733
2066
|
const started = await input.peer.request("turn/start", turnParams);
|
|
1734
|
-
|
|
2067
|
+
nativeTurnId = CodexStartedTurnSchema.parse(started).turn.id;
|
|
2068
|
+
turn.codexTurnId = nativeTurnId;
|
|
1735
2069
|
} catch (error) {
|
|
1736
2070
|
if (input.getTurn() === turn)
|
|
1737
2071
|
input.setTurn(undefined);
|
|
1738
2072
|
throw error;
|
|
1739
2073
|
}
|
|
1740
2074
|
return {
|
|
2075
|
+
nativeTurnId,
|
|
1741
2076
|
deltas: turn.channel,
|
|
1742
2077
|
async interrupt() {
|
|
1743
|
-
turn
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
turnId: turn.codexTurnId
|
|
1749
|
-
});
|
|
1750
|
-
}
|
|
2078
|
+
interruptLocalCodexTurn(turn, nativeTurnId);
|
|
2079
|
+
await input.peer.request("turn/interrupt", {
|
|
2080
|
+
threadId: input.threadId,
|
|
2081
|
+
turnId: nativeTurnId
|
|
2082
|
+
});
|
|
1751
2083
|
},
|
|
1752
2084
|
async respond(interactionId, rawReply) {
|
|
1753
|
-
|
|
1754
|
-
const waiting = turn.pending.get(interactionId);
|
|
1755
|
-
if (waiting === undefined)
|
|
1756
|
-
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
1757
|
-
if (CODEX_APPROVAL_REQUESTS.has(waiting.detail.method)) {
|
|
1758
|
-
if (reply.kind === "input")
|
|
1759
|
-
throw new TypeError("A Codex approval is approved or denied, not answered with input");
|
|
1760
|
-
answerEngineRequest(turn, interactionId, {
|
|
1761
|
-
decision: reply.kind === "approve" ? CODEX_APPROVAL_DECISION.approve : CODEX_APPROVAL_DECISION.deny
|
|
1762
|
-
});
|
|
1763
|
-
} else {
|
|
1764
|
-
if (reply.kind !== "input")
|
|
1765
|
-
throw new TypeError("A Codex input request is answered with input");
|
|
1766
|
-
answerEngineRequest(turn, interactionId, {
|
|
1767
|
-
answers: CodexUserInputAnswersSchema.parse(reply.value)
|
|
1768
|
-
});
|
|
1769
|
-
}
|
|
2085
|
+
answerActiveCodexTurnRequest(turn, interactionId, rawReply);
|
|
1770
2086
|
}
|
|
1771
2087
|
};
|
|
1772
2088
|
}
|
|
1773
2089
|
});
|
|
1774
2090
|
}
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
let current;
|
|
1779
|
-
let dead;
|
|
1780
|
-
let closing = false;
|
|
1781
|
-
let connected;
|
|
1782
|
-
try {
|
|
1783
|
-
connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
|
|
1784
|
-
profileId: profile.profileId,
|
|
1785
|
-
limits: config.limits,
|
|
1786
|
-
getTurn: () => current,
|
|
1787
|
-
clearTurn: () => {
|
|
1788
|
-
current = undefined;
|
|
1789
|
-
}
|
|
1790
|
-
}), (error) => {
|
|
1791
|
-
dead = error;
|
|
1792
|
-
const turn = current;
|
|
1793
|
-
current = undefined;
|
|
1794
|
-
loseEngineTurn(turn, codexStopped, error);
|
|
1795
|
-
linked.abort();
|
|
1796
|
-
});
|
|
1797
|
-
} catch (error) {
|
|
1798
|
-
linked.release();
|
|
1799
|
-
throw error;
|
|
2091
|
+
function validateCodexOpenInput(input) {
|
|
2092
|
+
if (input.nativeThreadId !== undefined && input.forkFrom !== undefined) {
|
|
2093
|
+
throw new TypeError("[stitchkit] CodexDriver.open: nativeThreadId and forkFrom are mutually exclusive");
|
|
1800
2094
|
}
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
2095
|
+
if (input.forkFrom !== undefined) {
|
|
2096
|
+
if (typeof input.forkFrom.threadId !== "string" || input.forkFrom.threadId.trim().length === 0) {
|
|
2097
|
+
throw new TypeError("[stitchkit] CodexDriver.open: forkFrom.threadId must be a non-empty string");
|
|
2098
|
+
}
|
|
2099
|
+
validateCodexForkBounds(input.forkFrom, "CodexDriver.open");
|
|
2100
|
+
validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
function mergeOpenThreadPolicy(config, forkFrom, dynamicOverrides) {
|
|
2104
|
+
const basePolicy = {
|
|
2105
|
+
...config.model !== undefined && { model: config.model },
|
|
2106
|
+
...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
|
|
2107
|
+
...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
|
|
2108
|
+
...config.sandbox !== undefined && { sandbox: config.sandbox },
|
|
2109
|
+
...config.developerInstructions !== undefined && {
|
|
2110
|
+
developerInstructions: config.developerInstructions
|
|
2111
|
+
},
|
|
2112
|
+
...config.runtimeWorkspaceRoots !== undefined && {
|
|
2113
|
+
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
2114
|
+
},
|
|
2115
|
+
...config.config !== undefined && { config: config.config }
|
|
2116
|
+
};
|
|
2117
|
+
const withFork = forkFrom === undefined ? basePolicy : {
|
|
2118
|
+
...basePolicy,
|
|
2119
|
+
...forkFrom.model !== undefined && { model: forkFrom.model },
|
|
2120
|
+
...forkFrom.modelProvider !== undefined && {
|
|
2121
|
+
modelProvider: forkFrom.modelProvider
|
|
2122
|
+
},
|
|
2123
|
+
...forkFrom.approvalPolicy !== undefined && {
|
|
2124
|
+
approvalPolicy: forkFrom.approvalPolicy
|
|
2125
|
+
},
|
|
2126
|
+
...forkFrom.sandbox !== undefined && { sandbox: forkFrom.sandbox },
|
|
2127
|
+
...forkFrom.developerInstructions !== undefined && {
|
|
2128
|
+
developerInstructions: forkFrom.developerInstructions
|
|
2129
|
+
},
|
|
2130
|
+
...forkFrom.runtimeWorkspaceRoots !== undefined && {
|
|
2131
|
+
runtimeWorkspaceRoots: forkFrom.runtimeWorkspaceRoots
|
|
2132
|
+
},
|
|
2133
|
+
...basePolicy.config !== undefined || forkFrom.config !== undefined ? { config: { ...basePolicy.config ?? {}, ...forkFrom.config ?? {} } } : {}
|
|
2134
|
+
};
|
|
2135
|
+
return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
|
|
2136
|
+
}
|
|
2137
|
+
function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
|
|
2138
|
+
const threadParams = {
|
|
2139
|
+
cwd: input.cwd,
|
|
2140
|
+
...mergeOpenThreadPolicy(config, input.forkFrom, dynamicOverrides)
|
|
2141
|
+
};
|
|
2142
|
+
if (input.forkFrom !== undefined) {
|
|
2143
|
+
const fork = input.forkFrom;
|
|
2144
|
+
return peer.request("thread/fork", {
|
|
2145
|
+
threadId: fork.threadId,
|
|
2146
|
+
excludeTurns: fork.excludeTurns ?? true,
|
|
2147
|
+
...threadParams,
|
|
2148
|
+
...fork.beforeTurnId !== undefined && { beforeTurnId: fork.beforeTurnId },
|
|
2149
|
+
...fork.lastTurnId !== undefined && { lastTurnId: fork.lastTurnId },
|
|
2150
|
+
...fork.deferGoalContinuation !== undefined && {
|
|
2151
|
+
deferGoalContinuation: fork.deferGoalContinuation
|
|
2152
|
+
}
|
|
2153
|
+
});
|
|
2154
|
+
}
|
|
2155
|
+
if (input.nativeThreadId !== undefined) {
|
|
2156
|
+
return peer.request("thread/resume", {
|
|
2157
|
+
threadId: input.nativeThreadId,
|
|
2158
|
+
excludeTurns: true,
|
|
2159
|
+
...threadParams
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
return peer.request("thread/start", threadParams);
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
// src/agent-executor/codex/control-client.ts
|
|
2166
|
+
function assertOptionalItemsCursor(cursor, caller) {
|
|
2167
|
+
if (cursor === undefined || cursor === null)
|
|
2168
|
+
return;
|
|
2169
|
+
if (typeof cursor === "string") {
|
|
2170
|
+
if (cursor.trim().length === 0) {
|
|
2171
|
+
throw new TypeError(`[stitchkit] ${caller}: cursor must be a non-empty string`);
|
|
2172
|
+
}
|
|
2173
|
+
return;
|
|
2174
|
+
}
|
|
2175
|
+
if (typeof cursor !== "object" || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
|
|
2176
|
+
throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
function createCodexControlClient(input) {
|
|
2180
|
+
const call = async (method, params) => {
|
|
2181
|
+
input.ensureAlive();
|
|
2182
|
+
return input.peer.request(method, params);
|
|
2183
|
+
};
|
|
2184
|
+
return {
|
|
2185
|
+
readConfig(params) {
|
|
2186
|
+
return call("config/read", {
|
|
2187
|
+
...params?.cwd !== undefined && { cwd: params.cwd },
|
|
2188
|
+
...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
|
|
2189
|
+
});
|
|
2190
|
+
},
|
|
2191
|
+
async readThread(params) {
|
|
2192
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
|
|
2193
|
+
return call("thread/read", {
|
|
2194
|
+
threadId,
|
|
2195
|
+
...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
|
|
2196
|
+
});
|
|
2197
|
+
},
|
|
2198
|
+
listCollaborationModes() {
|
|
2199
|
+
return call("collaborationMode/list", {});
|
|
2200
|
+
},
|
|
2201
|
+
async listTurns(params) {
|
|
2202
|
+
const caller = "CodexControlClient.listTurns";
|
|
2203
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2204
|
+
assertOptionalLimit(params.limit, caller);
|
|
2205
|
+
if (params.cursor !== undefined && params.cursor !== null && typeof params.cursor !== "string") {
|
|
2206
|
+
throw new TypeError(`[stitchkit] ${caller}: cursor must be a string or null`);
|
|
2207
|
+
}
|
|
2208
|
+
return call("thread/turns/list", {
|
|
2209
|
+
threadId,
|
|
2210
|
+
...params.cursor !== undefined && { cursor: params.cursor },
|
|
2211
|
+
...params.limit !== undefined && { limit: params.limit },
|
|
2212
|
+
...params.itemsView !== undefined && { itemsView: params.itemsView },
|
|
2213
|
+
...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
|
|
2214
|
+
});
|
|
2215
|
+
},
|
|
2216
|
+
async listItems(params) {
|
|
2217
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listItems");
|
|
2218
|
+
assertOptionalLimit(params.limit, "CodexControlClient.listItems");
|
|
2219
|
+
assertOptionalNonEmptyString(params.turnId, "turnId", "CodexControlClient.listItems");
|
|
2220
|
+
assertOptionalItemsCursor(params.cursor, "CodexControlClient.listItems");
|
|
2221
|
+
return call("thread/items/list", {
|
|
2222
|
+
threadId,
|
|
2223
|
+
...params.turnId !== undefined && { turnId: params.turnId },
|
|
2224
|
+
...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
|
|
2225
|
+
...params.limit !== undefined && { limit: params.limit },
|
|
2226
|
+
...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
|
|
2227
|
+
...params.deferOutput !== undefined && {
|
|
2228
|
+
deferOutput: safeJsonValue(params.deferOutput)
|
|
2229
|
+
}
|
|
2230
|
+
});
|
|
2231
|
+
},
|
|
2232
|
+
listMcpServerStatus(params) {
|
|
2233
|
+
return call("mcpServerStatus/list", {
|
|
2234
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
2235
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
2236
|
+
...params?.threadId !== undefined && { threadId: params.threadId },
|
|
2237
|
+
...params?.serverName !== undefined && { serverName: params.serverName },
|
|
2238
|
+
...params?.detail !== undefined && { detail: params.detail }
|
|
2239
|
+
});
|
|
2240
|
+
},
|
|
2241
|
+
listSkills(params) {
|
|
2242
|
+
return call("skills/list", {
|
|
2243
|
+
...params?.cwds !== undefined && { cwds: [...params.cwds] },
|
|
2244
|
+
...params?.forceReload !== undefined && { forceReload: params.forceReload }
|
|
2245
|
+
});
|
|
2246
|
+
},
|
|
2247
|
+
listModels(params) {
|
|
2248
|
+
return call("model/list", {
|
|
2249
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
2250
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
2251
|
+
...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
|
|
2252
|
+
...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
|
|
2253
|
+
});
|
|
2254
|
+
},
|
|
2255
|
+
readAccount(params) {
|
|
2256
|
+
return call("account/read", {
|
|
2257
|
+
...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
|
|
2258
|
+
});
|
|
2259
|
+
},
|
|
2260
|
+
readRateLimits() {
|
|
2261
|
+
return call("account/rateLimits/read");
|
|
2262
|
+
},
|
|
2263
|
+
async resumeThread(params) {
|
|
2264
|
+
input.ensureAlive();
|
|
2265
|
+
return call("thread/resume", buildCodexResumeThreadParams(params));
|
|
2266
|
+
},
|
|
2267
|
+
async steerTurn(params) {
|
|
2268
|
+
input.ensureAlive();
|
|
2269
|
+
const caller = "CodexControlClient.steerTurn";
|
|
2270
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2271
|
+
const expectedTurnId = assertRequiredNonEmptyString(params.expectedTurnId, "expectedTurnId", caller);
|
|
2272
|
+
assertOptionalNonEmptyString(params.clientId, "clientId", caller);
|
|
2273
|
+
const parts = await inlineCodexParts(params.input, {
|
|
2274
|
+
...input.imageOptions,
|
|
2275
|
+
driverLabel: "The Codex driver",
|
|
2276
|
+
signal: input.signal
|
|
2277
|
+
});
|
|
2278
|
+
input.ensureAlive();
|
|
2279
|
+
return sendCodexTurnSteer(input.peer, {
|
|
2280
|
+
threadId,
|
|
2281
|
+
expectedTurnId,
|
|
2282
|
+
parts,
|
|
2283
|
+
...params.clientId !== undefined && { clientId: params.clientId }
|
|
2284
|
+
});
|
|
2285
|
+
},
|
|
2286
|
+
...createCodexThreadControlMethods(call, {
|
|
2287
|
+
ensureAlive: input.ensureAlive,
|
|
2288
|
+
...input.onBeforeInterruptTurn !== undefined && {
|
|
2289
|
+
onBeforeInterruptTurn: input.onBeforeInterruptTurn
|
|
2290
|
+
}
|
|
2291
|
+
})
|
|
2292
|
+
};
|
|
2293
|
+
}
|
|
2294
|
+
function bindCodexSessionThreadControls(controlClient, threadId) {
|
|
2295
|
+
return {
|
|
2296
|
+
readThread(params) {
|
|
2297
|
+
return controlClient.readThread({
|
|
2298
|
+
...params,
|
|
2299
|
+
threadId: params?.threadId ?? threadId
|
|
2300
|
+
});
|
|
2301
|
+
},
|
|
2302
|
+
listTurns(params) {
|
|
2303
|
+
return controlClient.listTurns({
|
|
2304
|
+
...params,
|
|
2305
|
+
threadId: params?.threadId ?? threadId
|
|
2306
|
+
});
|
|
2307
|
+
},
|
|
2308
|
+
listItems(params) {
|
|
2309
|
+
return controlClient.listItems({
|
|
2310
|
+
...params,
|
|
2311
|
+
threadId: params?.threadId ?? threadId
|
|
2312
|
+
});
|
|
2313
|
+
},
|
|
2314
|
+
resumeThread(params) {
|
|
2315
|
+
return controlClient.resumeThread({
|
|
2316
|
+
...params,
|
|
2317
|
+
threadId: params?.threadId ?? threadId
|
|
2318
|
+
});
|
|
2319
|
+
},
|
|
2320
|
+
revertThread(params) {
|
|
2321
|
+
return controlClient.revertThread({
|
|
2322
|
+
...params,
|
|
2323
|
+
threadId: params.threadId ?? threadId
|
|
2324
|
+
});
|
|
2325
|
+
},
|
|
2326
|
+
injectItems(params) {
|
|
2327
|
+
return controlClient.injectItems({
|
|
2328
|
+
...params,
|
|
2329
|
+
threadId: params.threadId ?? threadId
|
|
2330
|
+
});
|
|
2331
|
+
},
|
|
2332
|
+
unsubscribeThread(params) {
|
|
2333
|
+
return controlClient.unsubscribeThread({
|
|
2334
|
+
threadId: params?.threadId ?? threadId
|
|
2335
|
+
});
|
|
2336
|
+
},
|
|
2337
|
+
archiveThread(params) {
|
|
2338
|
+
return controlClient.archiveThread({
|
|
2339
|
+
threadId: params?.threadId ?? threadId
|
|
2340
|
+
});
|
|
2341
|
+
},
|
|
2342
|
+
unarchiveThread(params) {
|
|
2343
|
+
return controlClient.unarchiveThread({
|
|
2344
|
+
threadId: params?.threadId ?? threadId
|
|
2345
|
+
});
|
|
2346
|
+
},
|
|
2347
|
+
updateThreadMetadata(params) {
|
|
2348
|
+
return controlClient.updateThreadMetadata({
|
|
2349
|
+
...params,
|
|
2350
|
+
threadId: params?.threadId ?? threadId
|
|
2351
|
+
});
|
|
2352
|
+
},
|
|
2353
|
+
setThreadName(params) {
|
|
2354
|
+
return controlClient.setThreadName({
|
|
2355
|
+
...params,
|
|
2356
|
+
threadId: params.threadId ?? threadId
|
|
2357
|
+
});
|
|
2358
|
+
},
|
|
2359
|
+
interruptTurn(params) {
|
|
2360
|
+
return controlClient.interruptTurn({
|
|
2361
|
+
...params,
|
|
2362
|
+
threadId: params.threadId ?? threadId
|
|
2363
|
+
});
|
|
2364
|
+
},
|
|
2365
|
+
compactThread(params) {
|
|
2366
|
+
return controlClient.compactThread({
|
|
2367
|
+
threadId: params?.threadId ?? threadId
|
|
2368
|
+
});
|
|
2369
|
+
}
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
|
|
2373
|
+
// src/agent-executor/codex/classify.ts
|
|
2374
|
+
var raw = (type) => ({ source: "codex", type });
|
|
2375
|
+
var CODEX_TOOL_ITEMS = new Set([
|
|
2376
|
+
"commandExecution",
|
|
2377
|
+
"fileChange",
|
|
2378
|
+
"mcpToolCall",
|
|
2379
|
+
"dynamicToolCall",
|
|
2380
|
+
"collabAgentToolCall",
|
|
2381
|
+
"webSearch",
|
|
2382
|
+
"imageView",
|
|
2383
|
+
"sleep",
|
|
2384
|
+
"imageGeneration",
|
|
2385
|
+
"functionCallOutput"
|
|
2386
|
+
]);
|
|
2387
|
+
var STATUSLESS_TOOL_ITEMS = new Set([
|
|
2388
|
+
"webSearch",
|
|
2389
|
+
"imageView",
|
|
2390
|
+
"sleep",
|
|
2391
|
+
"functionCallOutput"
|
|
2392
|
+
]);
|
|
2393
|
+
var CODEX_CONTENT_ITEMS = new Set([
|
|
2394
|
+
"agentMessage",
|
|
2395
|
+
"reasoning",
|
|
2396
|
+
"userMessage",
|
|
2397
|
+
"plan",
|
|
2398
|
+
"contextCompaction",
|
|
2399
|
+
"hookPrompt",
|
|
2400
|
+
"subAgentActivity",
|
|
2401
|
+
"enteredReviewMode",
|
|
2402
|
+
"exitedReviewMode"
|
|
2403
|
+
]);
|
|
2404
|
+
var KNOWN_CODEX_ERROR_CODES = new Set([
|
|
2405
|
+
"contextWindowExceeded",
|
|
2406
|
+
"sessionBudgetExceeded",
|
|
2407
|
+
"usageLimitExceeded",
|
|
2408
|
+
"rateLimitExceeded",
|
|
2409
|
+
"flexUnavailable",
|
|
2410
|
+
"serverOverloaded",
|
|
2411
|
+
"modelNotFound",
|
|
2412
|
+
"policyCapacityUnavailable",
|
|
2413
|
+
"cyberPolicy",
|
|
2414
|
+
"bioPolicy",
|
|
2415
|
+
"misalignmentPolicyViolation",
|
|
2416
|
+
"tooManyDenials",
|
|
2417
|
+
"internalServerError",
|
|
2418
|
+
"unauthorized",
|
|
2419
|
+
"badRequest",
|
|
2420
|
+
"threadRollbackFailed",
|
|
2421
|
+
"sandboxError",
|
|
2422
|
+
"other",
|
|
2423
|
+
"inferenceHookDenied"
|
|
2424
|
+
]);
|
|
2425
|
+
var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
|
|
2426
|
+
"httpConnectionFailed",
|
|
2427
|
+
"responseStreamConnectionFailed",
|
|
2428
|
+
"responseStreamDisconnected",
|
|
2429
|
+
"responseTooManyFailedAttempts",
|
|
2430
|
+
"activeTurnNotSteerable"
|
|
2431
|
+
]);
|
|
2432
|
+
var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
|
|
2433
|
+
function toolName(item) {
|
|
2434
|
+
if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
|
|
2435
|
+
return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
|
|
2436
|
+
}
|
|
2437
|
+
if (item.type === "functionCallOutput") {
|
|
2438
|
+
return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
|
|
2439
|
+
}
|
|
2440
|
+
return item.type;
|
|
2441
|
+
}
|
|
2442
|
+
function toolInput(item) {
|
|
2443
|
+
const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
|
|
2444
|
+
return safeJsonValue(rest);
|
|
2445
|
+
}
|
|
2446
|
+
function isKnownCodexErrorInfo(info) {
|
|
2447
|
+
if (typeof info === "string")
|
|
2448
|
+
return KNOWN_CODEX_ERROR_CODES.has(info);
|
|
2449
|
+
if (typeof info === "object" && info !== null && !Array.isArray(info)) {
|
|
2450
|
+
const keys = Object.keys(info);
|
|
2451
|
+
return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
|
|
2452
|
+
}
|
|
2453
|
+
return false;
|
|
2454
|
+
}
|
|
2455
|
+
function formatCodexErrorInfo(info) {
|
|
2456
|
+
if (info === null || info === undefined)
|
|
2457
|
+
return;
|
|
2458
|
+
if (typeof info === "string") {
|
|
2459
|
+
const trimmed = info.trim();
|
|
2460
|
+
return trimmed.length > 0 ? trimmed.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS) : undefined;
|
|
2461
|
+
}
|
|
2462
|
+
try {
|
|
2463
|
+
const serialized = JSON.stringify(safeJsonValue(info));
|
|
2464
|
+
if (serialized === undefined || serialized.length === 0)
|
|
2465
|
+
return;
|
|
2466
|
+
return serialized.length > MAX_ERROR_INFO_SUMMARY_CHARS ? `${serialized.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS - 1)}…` : serialized;
|
|
2467
|
+
} catch {
|
|
2468
|
+
return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
function codexFailureMessage(turn) {
|
|
2472
|
+
const rawMessage = turn.error?.message.trim() ?? "";
|
|
2473
|
+
const info = turn.error?.codexErrorInfo;
|
|
2474
|
+
const infoSummary = formatCodexErrorInfo(info);
|
|
2475
|
+
if (rawMessage.length > 0) {
|
|
2476
|
+
if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
|
|
2477
|
+
return `${rawMessage} (${infoSummary})`;
|
|
2478
|
+
}
|
|
2479
|
+
return rawMessage;
|
|
2480
|
+
}
|
|
2481
|
+
if (infoSummary !== undefined) {
|
|
2482
|
+
return `Codex ended the turn ${turn.status} (${infoSummary})`;
|
|
2483
|
+
}
|
|
2484
|
+
return `Codex ended the turn ${turn.status}`;
|
|
2485
|
+
}
|
|
2486
|
+
function httpStatusOf(value, depth = 0) {
|
|
2487
|
+
if (depth > 3 || typeof value !== "object" || value === null)
|
|
2488
|
+
return;
|
|
2489
|
+
const direct = Reflect.get(value, "httpStatusCode");
|
|
2490
|
+
if (typeof direct === "number")
|
|
2491
|
+
return direct;
|
|
2492
|
+
for (const nested of Object.values(value)) {
|
|
2493
|
+
const found = httpStatusOf(nested, depth + 1);
|
|
2494
|
+
if (found !== undefined)
|
|
2495
|
+
return found;
|
|
2496
|
+
}
|
|
2497
|
+
return;
|
|
2498
|
+
}
|
|
2499
|
+
function failureKind(info) {
|
|
2500
|
+
if (info === "unauthorized")
|
|
2501
|
+
return "authRequired";
|
|
2502
|
+
if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "sessionBudgetExceeded")
|
|
2503
|
+
return "rateLimited";
|
|
2504
|
+
const status = httpStatusOf(info);
|
|
2505
|
+
if (status === 401 || status === 403)
|
|
2506
|
+
return "authRequired";
|
|
2507
|
+
if (status === 429)
|
|
2508
|
+
return "rateLimited";
|
|
2509
|
+
return "restartRecommended";
|
|
2510
|
+
}
|
|
2511
|
+
function normalizeCodexTokenTotals(rawTotals) {
|
|
2512
|
+
if (rawTotals === undefined)
|
|
2513
|
+
return;
|
|
2514
|
+
const normalized = {
|
|
2515
|
+
...rawTotals.inputTokens !== undefined && { inputTokens: rawTotals.inputTokens },
|
|
2516
|
+
...rawTotals.outputTokens !== undefined && { outputTokens: rawTotals.outputTokens },
|
|
2517
|
+
...rawTotals.cachedInputTokens !== undefined && {
|
|
2518
|
+
cachedInputTokens: rawTotals.cachedInputTokens
|
|
2519
|
+
},
|
|
2520
|
+
...rawTotals.cacheWriteInputTokens !== undefined && {
|
|
2521
|
+
cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
|
|
2522
|
+
},
|
|
2523
|
+
...rawTotals.reasoningOutputTokens !== undefined && {
|
|
2524
|
+
thinkingTokens: rawTotals.reasoningOutputTokens
|
|
2525
|
+
},
|
|
2526
|
+
...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
|
|
2527
|
+
};
|
|
2528
|
+
return Object.keys(normalized).length > 0 ? normalized : undefined;
|
|
2529
|
+
}
|
|
2530
|
+
function classifyCodexTokenUsage(params, base) {
|
|
2531
|
+
const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
|
|
2532
|
+
const normalizedTotal = normalizeCodexTokenTotals(total);
|
|
2533
|
+
return {
|
|
2534
|
+
kind: "deltas",
|
|
2535
|
+
deltas: [
|
|
2536
|
+
{
|
|
2537
|
+
type: "usage",
|
|
2538
|
+
...base,
|
|
2539
|
+
itemId: "usage",
|
|
2540
|
+
raw: raw("thread/tokenUsage/updated"),
|
|
2541
|
+
inputTokens: last.inputTokens,
|
|
2542
|
+
outputTokens: last.outputTokens,
|
|
2543
|
+
...last.cachedInputTokens !== undefined && {
|
|
2544
|
+
cachedInputTokens: last.cachedInputTokens
|
|
2545
|
+
},
|
|
2546
|
+
...last.cacheWriteInputTokens !== undefined && {
|
|
2547
|
+
cacheCreationInputTokens: last.cacheWriteInputTokens
|
|
2548
|
+
},
|
|
2549
|
+
...last.reasoningOutputTokens !== undefined && {
|
|
2550
|
+
thinkingTokens: last.reasoningOutputTokens
|
|
2551
|
+
},
|
|
2552
|
+
...last.totalTokens !== undefined && { totalTokens: last.totalTokens },
|
|
2553
|
+
...normalizedTotal !== undefined && { total: normalizedTotal }
|
|
2554
|
+
}
|
|
2555
|
+
]
|
|
2556
|
+
};
|
|
2557
|
+
}
|
|
2558
|
+
function classifyCodexNotification(method, params, state) {
|
|
2559
|
+
const base = { turnId: state.turnId };
|
|
2560
|
+
switch (method) {
|
|
2561
|
+
case "item/agentMessage/delta": {
|
|
2562
|
+
const p = CodexNotificationParams[method].parse(params);
|
|
2563
|
+
return {
|
|
2564
|
+
kind: "deltas",
|
|
2565
|
+
deltas: [{ type: "text", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }]
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
case "item/reasoning/textDelta":
|
|
2569
|
+
case "item/reasoning/summaryTextDelta": {
|
|
2570
|
+
const p = CodexNotificationParams[method].parse(params);
|
|
2571
|
+
return {
|
|
2572
|
+
kind: "deltas",
|
|
2573
|
+
deltas: [
|
|
2574
|
+
{ type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
|
|
2575
|
+
]
|
|
2576
|
+
};
|
|
2577
|
+
}
|
|
2578
|
+
case "item/started":
|
|
2579
|
+
case "item/completed": {
|
|
2580
|
+
const { item } = CodexNotificationParams[method].parse(params);
|
|
2581
|
+
if (CODEX_CONTENT_ITEMS.has(item.type))
|
|
2582
|
+
return { kind: "ignore", reason: `${method} ${item.type}` };
|
|
2583
|
+
if (!CODEX_TOOL_ITEMS.has(item.type)) {
|
|
2584
|
+
return {
|
|
2585
|
+
kind: "unhandled",
|
|
2586
|
+
delta: {
|
|
2587
|
+
type: "error",
|
|
2588
|
+
...base,
|
|
2589
|
+
itemId: `unhandled:${item.id}`,
|
|
2590
|
+
raw: raw(`${method}/${item.type}`),
|
|
2591
|
+
kind: "unhandled",
|
|
2592
|
+
message: `Codex item ${item.type} is not known to this driver`
|
|
2593
|
+
}
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
if (method === "item/started") {
|
|
2597
|
+
return {
|
|
2598
|
+
kind: "deltas",
|
|
2599
|
+
deltas: [
|
|
2600
|
+
{
|
|
2601
|
+
type: "tool-call",
|
|
2602
|
+
...base,
|
|
2603
|
+
itemId: `call:${item.id}`,
|
|
2604
|
+
raw: raw(method),
|
|
2605
|
+
callId: item.id,
|
|
2606
|
+
toolName: toolName(item),
|
|
2607
|
+
input: toolInput(item)
|
|
2608
|
+
}
|
|
2609
|
+
]
|
|
2610
|
+
};
|
|
2611
|
+
}
|
|
2612
|
+
const status = Reflect.get(item, "status");
|
|
2613
|
+
const failure = Reflect.get(item, "failure");
|
|
2614
|
+
const output = failure ?? Reflect.get(item, "aggregatedOutput") ?? Reflect.get(item, "output") ?? Reflect.get(item, "savedPath") ?? Reflect.get(item, "fileId") ?? Reflect.get(item, "result") ?? Reflect.get(item, "results") ?? Reflect.get(item, "contentItems") ?? Reflect.get(item, "changes") ?? Reflect.get(item, "agentsStates") ?? Reflect.get(item, "error");
|
|
2615
|
+
const hasFailure = failure !== undefined && failure !== null;
|
|
2616
|
+
const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
|
|
2617
|
+
return {
|
|
2618
|
+
kind: "deltas",
|
|
2619
|
+
deltas: [
|
|
2620
|
+
{
|
|
2621
|
+
type: "tool-result",
|
|
2622
|
+
...base,
|
|
2623
|
+
itemId: `result:${item.id}`,
|
|
2624
|
+
raw: raw(method),
|
|
2625
|
+
callId: item.id,
|
|
2626
|
+
toolName: toolName(item),
|
|
2627
|
+
outcome,
|
|
2628
|
+
...output !== undefined && output !== null && {
|
|
2629
|
+
output: safeJsonValue(output)
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
]
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
2635
|
+
case "turn/completed": {
|
|
2636
|
+
const { turn } = CodexNotificationParams[method].parse(params);
|
|
2637
|
+
const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
|
|
2638
|
+
const deltas = [];
|
|
2639
|
+
if (outcome === "failed") {
|
|
2640
|
+
deltas.push({
|
|
2641
|
+
type: "error",
|
|
2642
|
+
...base,
|
|
2643
|
+
itemId: "failure",
|
|
2644
|
+
raw: raw(method),
|
|
2645
|
+
kind: failureKind(turn.error?.codexErrorInfo),
|
|
2646
|
+
message: codexFailureMessage(turn)
|
|
2647
|
+
});
|
|
2648
|
+
}
|
|
2649
|
+
deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
|
|
2650
|
+
return { kind: "end", deltas, outcome };
|
|
2651
|
+
}
|
|
2652
|
+
case "thread/tokenUsage/updated":
|
|
2653
|
+
return classifyCodexTokenUsage(params, base);
|
|
2654
|
+
case "serverRequest/resolved":
|
|
2655
|
+
return {
|
|
2656
|
+
kind: "resolved",
|
|
2657
|
+
requestId: String(CodexNotificationParams[method].parse(params).requestId)
|
|
2658
|
+
};
|
|
2659
|
+
case "account/rateLimits/updated": {
|
|
2660
|
+
const parsed = CodexNotificationParams[method].parse(params);
|
|
2661
|
+
return {
|
|
2662
|
+
kind: "limits",
|
|
2663
|
+
rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
|
|
2664
|
+
rateLimits: parsed.rateLimits,
|
|
2665
|
+
rateLimitsByLimitId: parsed.rateLimitsByLimitId
|
|
2666
|
+
} : parsed.rateLimits
|
|
2667
|
+
};
|
|
2668
|
+
}
|
|
2669
|
+
default:
|
|
2670
|
+
if (CODEX_QUIET_NOTIFICATIONS.has(method))
|
|
2671
|
+
return { kind: "ignore", reason: method };
|
|
2672
|
+
return {
|
|
2673
|
+
kind: "unhandled",
|
|
2674
|
+
delta: {
|
|
2675
|
+
type: "error",
|
|
2676
|
+
...base,
|
|
2677
|
+
itemId: `unhandled:${method}`,
|
|
2678
|
+
raw: raw(method),
|
|
2679
|
+
kind: "unhandled",
|
|
2680
|
+
message: `Codex notification ${method} is not known to this driver`
|
|
2681
|
+
}
|
|
2682
|
+
};
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
|
|
2686
|
+
// src/agent-executor/codex/handlers.ts
|
|
2687
|
+
var JSON_RPC_INTERNAL_ERROR = -32603;
|
|
2688
|
+
var MAX_EXTERNAL_PENDING_REQUESTS = 256;
|
|
2689
|
+
function emitCodexNotification(state, method, params, duringActiveTurn, deltas) {
|
|
2690
|
+
if (state.onNotification === undefined)
|
|
2691
|
+
return;
|
|
2692
|
+
invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
|
|
2693
|
+
}
|
|
2694
|
+
function handleCodexNotification(state, method, params) {
|
|
2695
|
+
const turn = state.getTurn();
|
|
2696
|
+
const duringActiveTurn = turn !== undefined;
|
|
2697
|
+
const effectiveTurnId = turn?.state.turnId ?? externalCodexTurnIdOf(params);
|
|
2698
|
+
let verdict;
|
|
2699
|
+
try {
|
|
2700
|
+
verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: effectiveTurnId, interruptRequested: false });
|
|
2701
|
+
} catch (error) {
|
|
2702
|
+
const errorDelta = {
|
|
2703
|
+
type: "error",
|
|
2704
|
+
turnId: effectiveTurnId,
|
|
2705
|
+
itemId: `unhandled:${method}`,
|
|
2706
|
+
raw: { source: "codex", type: method },
|
|
2707
|
+
kind: "unhandled",
|
|
2708
|
+
message: `Codex notification ${method} did not match schema: ${error instanceof Error ? error.message : String(error)}`
|
|
2709
|
+
};
|
|
2710
|
+
if (turn !== undefined)
|
|
2711
|
+
offerTurnDelta(turn.channel, errorDelta);
|
|
2712
|
+
emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
|
|
2713
|
+
return;
|
|
2714
|
+
}
|
|
2715
|
+
switch (verdict.kind) {
|
|
2716
|
+
case "limits":
|
|
2717
|
+
try {
|
|
2718
|
+
state.limits.set(state.profileId, mergeRateLimitEvent2({
|
|
2719
|
+
previous: state.limits.get(state.profileId),
|
|
2720
|
+
windows: codexPlanWindows(verdict.rateLimits),
|
|
2721
|
+
now: new Date
|
|
2722
|
+
}));
|
|
2723
|
+
emitCodexNotification(state, method, params, duringActiveTurn, []);
|
|
2724
|
+
} catch (error) {
|
|
2725
|
+
const errorDelta = {
|
|
2726
|
+
type: "error",
|
|
2727
|
+
turnId: effectiveTurnId,
|
|
2728
|
+
itemId: `unhandled:${method}`,
|
|
2729
|
+
raw: { source: "codex", type: method },
|
|
2730
|
+
kind: "unhandled",
|
|
2731
|
+
message: `Codex rate-limit update could not be merged: ${error instanceof Error ? error.message : String(error)}`
|
|
2732
|
+
};
|
|
2733
|
+
if (turn !== undefined)
|
|
2734
|
+
offerTurnDelta(turn.channel, errorDelta);
|
|
2735
|
+
emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
|
|
2736
|
+
}
|
|
2737
|
+
return;
|
|
2738
|
+
case "resolved": {
|
|
2739
|
+
const resolvedTurn = turn?.pending.delete(verdict.requestId) === true;
|
|
2740
|
+
const externalEntry = state.externalPending.get(verdict.requestId);
|
|
2741
|
+
const resolvedExternal = externalEntry !== undefined;
|
|
2742
|
+
if (resolvedExternal)
|
|
2743
|
+
state.externalPending.delete(verdict.requestId);
|
|
2744
|
+
const resolvedDelta = {
|
|
2745
|
+
type: "request-resolved",
|
|
2746
|
+
turnId: resolvedTurn ? turn?.state.turnId ?? effectiveTurnId : externalEntry?.turnId ?? effectiveTurnId,
|
|
2747
|
+
itemId: `resolved:${verdict.requestId}`,
|
|
2748
|
+
raw: { source: "codex", type: "serverRequest/resolved" },
|
|
2749
|
+
interactionId: verdict.requestId
|
|
2750
|
+
};
|
|
2751
|
+
if (resolvedTurn && turn !== undefined)
|
|
2752
|
+
offerTurnDelta(turn.channel, resolvedDelta);
|
|
2753
|
+
emitCodexNotification(state, method, params, duringActiveTurn, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
|
|
2754
|
+
return;
|
|
2755
|
+
}
|
|
2756
|
+
case "deltas":
|
|
2757
|
+
case "unhandled": {
|
|
2758
|
+
const emitted = verdict.kind === "deltas" ? verdict.deltas : [verdict.delta];
|
|
2759
|
+
if (turn !== undefined) {
|
|
2760
|
+
for (const delta of emitted)
|
|
2761
|
+
offerTurnDelta(turn.channel, delta);
|
|
2762
|
+
}
|
|
2763
|
+
emitCodexNotification(state, method, params, duringActiveTurn, emitted);
|
|
2764
|
+
return;
|
|
2765
|
+
}
|
|
2766
|
+
case "end":
|
|
2767
|
+
endEngineTurn(turn, codexStopped, verdict.deltas);
|
|
2768
|
+
state.clearTurn();
|
|
2769
|
+
emitCodexNotification(state, method, params, duringActiveTurn, verdict.deltas);
|
|
2770
|
+
return;
|
|
2771
|
+
case "ignore":
|
|
2772
|
+
emitCodexNotification(state, method, params, duringActiveTurn, []);
|
|
2773
|
+
return;
|
|
2774
|
+
}
|
|
2775
|
+
}
|
|
2776
|
+
function handleCodexRequest(state, method, params, id) {
|
|
2777
|
+
const turn = state.getTurn();
|
|
2778
|
+
if (!isKnownCodexRequestMethod(method)) {
|
|
2779
|
+
if (turn !== undefined) {
|
|
2780
|
+
offerTurnDelta(turn.channel, {
|
|
2781
|
+
type: "error",
|
|
2782
|
+
turnId: turn.state.turnId,
|
|
2783
|
+
itemId: `unhandled-request:${id}`,
|
|
2784
|
+
raw: { source: "codex", type: method },
|
|
2785
|
+
kind: "unhandled",
|
|
2786
|
+
message: `Codex request ${method} is not known to this driver; refused`
|
|
2787
|
+
});
|
|
2788
|
+
}
|
|
2789
|
+
throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
|
|
2790
|
+
}
|
|
2791
|
+
const interactionId = String(id);
|
|
2792
|
+
if (turn !== undefined) {
|
|
2793
|
+
const parsed = parseCodexServerRequest(method, params);
|
|
2794
|
+
const delta = {
|
|
2795
|
+
type: "request",
|
|
2796
|
+
turnId: turn.state.turnId,
|
|
2797
|
+
itemId: `request:${interactionId}`,
|
|
2798
|
+
raw: { source: "codex", type: method },
|
|
2799
|
+
interactionId,
|
|
2800
|
+
kind: parsed.kind,
|
|
2801
|
+
...parsed.deltaFields
|
|
2802
|
+
};
|
|
2803
|
+
const promise = new Promise((resolve) => {
|
|
2804
|
+
holdEngineRequest(turn, {
|
|
2805
|
+
interactionId,
|
|
2806
|
+
detail: parsed.detail,
|
|
2807
|
+
answeredBy: { source: "codex", type: method },
|
|
2808
|
+
delta: () => delta,
|
|
2809
|
+
refusal: codexStoppedAnswer(method),
|
|
2810
|
+
resolve
|
|
2811
|
+
});
|
|
2812
|
+
});
|
|
2813
|
+
if (state.serverRequestDelivery === "all" && state.onServerRequest !== undefined && turn.pending.has(interactionId)) {
|
|
2814
|
+
const observer = state.onServerRequest;
|
|
2815
|
+
invokeSafely(() => observer({
|
|
2816
|
+
interactionId,
|
|
2817
|
+
requestId: id,
|
|
2818
|
+
method,
|
|
2819
|
+
params,
|
|
2820
|
+
duringActiveTurn: true,
|
|
2821
|
+
delta,
|
|
2822
|
+
async respond(reply) {
|
|
2823
|
+
answerActiveCodexTurnRequest(turn, interactionId, reply);
|
|
2824
|
+
}
|
|
2825
|
+
}));
|
|
2826
|
+
}
|
|
2827
|
+
return promise;
|
|
2828
|
+
}
|
|
2829
|
+
const observer = state.onServerRequest;
|
|
2830
|
+
if (observer === undefined) {
|
|
2831
|
+
throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
|
|
2832
|
+
}
|
|
2833
|
+
if (state.externalPending.size >= MAX_EXTERNAL_PENDING_REQUESTS) {
|
|
2834
|
+
throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Too many pending external Codex server requests (limit ${MAX_EXTERNAL_PENDING_REQUESTS})`);
|
|
2835
|
+
}
|
|
2836
|
+
if (state.externalPending.has(interactionId)) {
|
|
2837
|
+
throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
|
|
2838
|
+
}
|
|
2839
|
+
const parsed = parseCodexServerRequest(method, params);
|
|
2840
|
+
const turnId = externalCodexTurnIdOf(params);
|
|
2841
|
+
const delta = {
|
|
2842
|
+
type: "request",
|
|
2843
|
+
turnId,
|
|
2844
|
+
itemId: `request:${interactionId}`,
|
|
2845
|
+
raw: { source: "codex", type: method },
|
|
2846
|
+
interactionId,
|
|
2847
|
+
kind: parsed.kind,
|
|
2848
|
+
...parsed.deltaFields
|
|
2849
|
+
};
|
|
2850
|
+
return new Promise((resolve, reject) => {
|
|
2851
|
+
const entry = { detail: parsed.detail, turnId, resolve };
|
|
2852
|
+
state.externalPending.set(interactionId, entry);
|
|
2853
|
+
const onObserverError = (error) => {
|
|
2854
|
+
if (state.externalPending.get(interactionId) !== entry)
|
|
2855
|
+
return;
|
|
2856
|
+
state.externalPending.delete(interactionId);
|
|
2857
|
+
if (error instanceof JsonRpcError2)
|
|
2858
|
+
reject(error);
|
|
2859
|
+
};
|
|
2860
|
+
try {
|
|
2861
|
+
const outcome = observer({
|
|
2862
|
+
interactionId,
|
|
2863
|
+
requestId: id,
|
|
2864
|
+
method,
|
|
2865
|
+
params,
|
|
2866
|
+
duringActiveTurn: false,
|
|
2867
|
+
delta,
|
|
2868
|
+
async respond(reply) {
|
|
2869
|
+
answerCodexSessionRequest({
|
|
2870
|
+
turn: undefined,
|
|
2871
|
+
externalPending: state.externalPending,
|
|
2872
|
+
expectedEntry: entry,
|
|
2873
|
+
interactionId,
|
|
2874
|
+
reply
|
|
2875
|
+
});
|
|
2876
|
+
}
|
|
2877
|
+
});
|
|
2878
|
+
if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
|
|
2879
|
+
Promise.resolve(outcome).catch(onObserverError);
|
|
2880
|
+
}
|
|
2881
|
+
} catch (error) {
|
|
2882
|
+
onObserverError(error);
|
|
2883
|
+
}
|
|
2884
|
+
});
|
|
2885
|
+
}
|
|
2886
|
+
function createCodexHandlers(state) {
|
|
2887
|
+
return {
|
|
2888
|
+
onNotification: (method, params) => handleCodexNotification(state, method, params),
|
|
2889
|
+
onRequest: (method, params, id) => handleCodexRequest(state, method, params, id)
|
|
2890
|
+
};
|
|
2891
|
+
}
|
|
2892
|
+
|
|
2893
|
+
// src/agent-executor/codex/session.ts
|
|
2894
|
+
async function openCodexSession(config, input) {
|
|
2895
|
+
validateCodexOpenInput(input);
|
|
2896
|
+
const profile = engineProfile("codex", input.profile);
|
|
2897
|
+
const linked = sessionAbort(input.signal);
|
|
2898
|
+
const externalPending = new Map;
|
|
2899
|
+
let current;
|
|
2900
|
+
let activeThreadId;
|
|
2901
|
+
let dead;
|
|
2902
|
+
let opened = false;
|
|
2903
|
+
let closing = false;
|
|
2904
|
+
let connected;
|
|
2905
|
+
try {
|
|
2906
|
+
connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
|
|
2907
|
+
profileId: profile.profileId,
|
|
2908
|
+
limits: config.limits,
|
|
2909
|
+
externalPending,
|
|
2910
|
+
getTurn: () => current,
|
|
2911
|
+
clearTurn: () => {
|
|
2912
|
+
current = undefined;
|
|
2913
|
+
},
|
|
2914
|
+
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
2915
|
+
...config.onServerRequest !== undefined && {
|
|
2916
|
+
onServerRequest: config.onServerRequest
|
|
2917
|
+
},
|
|
2918
|
+
...config.serverRequestDelivery !== undefined && {
|
|
2919
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
2920
|
+
}
|
|
2921
|
+
}), (error) => {
|
|
2922
|
+
const shouldNotify = opened && !closing && input.signal?.aborted !== true;
|
|
2923
|
+
dead = error;
|
|
2924
|
+
const turn = current;
|
|
2925
|
+
current = undefined;
|
|
2926
|
+
externalPending.clear();
|
|
2927
|
+
loseEngineTurn(turn, codexStopped, error);
|
|
2928
|
+
linked.abort();
|
|
2929
|
+
if (shouldNotify)
|
|
2930
|
+
invokeSafely(() => config.onDisconnect?.(error));
|
|
2931
|
+
}, input.onStartupPhase);
|
|
2932
|
+
} catch (error) {
|
|
2933
|
+
linked.release();
|
|
2934
|
+
throw error;
|
|
2935
|
+
}
|
|
2936
|
+
const { peer, providerPid, userAgent } = connected;
|
|
2937
|
+
const ensureAlive = () => {
|
|
2938
|
+
if (closing)
|
|
2939
|
+
throw new Error("The Codex session is closed");
|
|
2940
|
+
if (dead !== undefined)
|
|
2941
|
+
throw dead;
|
|
1807
2942
|
};
|
|
1808
2943
|
const stop = async (primary) => {
|
|
1809
2944
|
closing = true;
|
|
2945
|
+
externalPending.clear();
|
|
1810
2946
|
try {
|
|
1811
2947
|
await stopConnection(connected, primary);
|
|
1812
2948
|
} finally {
|
|
@@ -1814,7 +2950,16 @@ async function openCodexSession(config, input) {
|
|
|
1814
2950
|
linked.release();
|
|
1815
2951
|
}
|
|
1816
2952
|
};
|
|
1817
|
-
const controlClient = createCodexControlClient({
|
|
2953
|
+
const controlClient = createCodexControlClient({
|
|
2954
|
+
peer,
|
|
2955
|
+
imageOptions: config,
|
|
2956
|
+
signal: linked.signal,
|
|
2957
|
+
ensureAlive,
|
|
2958
|
+
onBeforeInterruptTurn: (targetThreadId, turnId) => {
|
|
2959
|
+
if (targetThreadId === activeThreadId)
|
|
2960
|
+
interruptLocalCodexTurn(current, turnId);
|
|
2961
|
+
}
|
|
2962
|
+
});
|
|
1818
2963
|
let threadId;
|
|
1819
2964
|
let threadContext;
|
|
1820
2965
|
let dynamicOverrides;
|
|
@@ -1825,36 +2970,18 @@ async function openCodexSession(config, input) {
|
|
|
1825
2970
|
cwd: input.cwd,
|
|
1826
2971
|
...input.nativeThreadId !== undefined && {
|
|
1827
2972
|
nativeThreadId: input.nativeThreadId
|
|
1828
|
-
}
|
|
2973
|
+
},
|
|
2974
|
+
...input.forkFrom !== undefined && { forkFrom: input.forkFrom }
|
|
1829
2975
|
})), linked.signal);
|
|
1830
2976
|
linked.signal.throwIfAborted();
|
|
1831
2977
|
}
|
|
1832
|
-
const
|
|
1833
|
-
|
|
1834
|
-
...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
|
|
1835
|
-
...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
|
|
1836
|
-
...config.sandbox !== undefined && { sandbox: config.sandbox },
|
|
1837
|
-
...config.developerInstructions !== undefined && {
|
|
1838
|
-
developerInstructions: config.developerInstructions
|
|
1839
|
-
},
|
|
1840
|
-
...config.runtimeWorkspaceRoots !== undefined && {
|
|
1841
|
-
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
1842
|
-
},
|
|
1843
|
-
...config.config !== undefined && { config: config.config }
|
|
1844
|
-
};
|
|
1845
|
-
const threadParams = {
|
|
1846
|
-
cwd: input.cwd,
|
|
1847
|
-
...buildCodexThreadPolicyParams(basePolicy, dynamicOverrides)
|
|
1848
|
-
};
|
|
1849
|
-
const opened = input.nativeThreadId ? await peer.request("thread/resume", {
|
|
1850
|
-
threadId: input.nativeThreadId,
|
|
1851
|
-
excludeTurns: true,
|
|
1852
|
-
...threadParams
|
|
1853
|
-
}) : await peer.request("thread/start", threadParams);
|
|
1854
|
-
const parsed = CodexStartedThreadSchema.parse(opened);
|
|
2978
|
+
const openedReply = await openCodexThreadRpc(peer, config, input, dynamicOverrides);
|
|
2979
|
+
const parsed = CodexStartedThreadSchema.parse(openedReply);
|
|
1855
2980
|
threadId = parsed.thread.id;
|
|
2981
|
+
activeThreadId = threadId;
|
|
1856
2982
|
threadContext = extractCodexThreadContext(parsed);
|
|
1857
2983
|
if (config.verifyThread !== undefined) {
|
|
2984
|
+
emitStartupPhase(input.onStartupPhase, "verifying");
|
|
1858
2985
|
await raceAbort(Promise.resolve(config.verifyThread({
|
|
1859
2986
|
nativeThreadId: threadId,
|
|
1860
2987
|
threadContext,
|
|
@@ -1862,11 +2989,14 @@ async function openCodexSession(config, input) {
|
|
|
1862
2989
|
})), linked.signal);
|
|
1863
2990
|
linked.signal.throwIfAborted();
|
|
1864
2991
|
}
|
|
2992
|
+
if (dead !== undefined)
|
|
2993
|
+
throw dead;
|
|
2994
|
+
linked.signal.throwIfAborted();
|
|
1865
2995
|
} catch (error) {
|
|
1866
2996
|
await stop({ error });
|
|
1867
2997
|
throw error;
|
|
1868
2998
|
}
|
|
1869
|
-
const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? config.modelProvider;
|
|
2999
|
+
const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? input.forkFrom?.modelProvider ?? config.modelProvider;
|
|
1870
3000
|
const startTurn = createCodexStartTurn({
|
|
1871
3001
|
config,
|
|
1872
3002
|
peer,
|
|
@@ -1887,67 +3017,624 @@ async function openCodexSession(config, input) {
|
|
|
1887
3017
|
ensureAlive,
|
|
1888
3018
|
getActiveTurn: () => current
|
|
1889
3019
|
});
|
|
3020
|
+
opened = true;
|
|
1890
3021
|
return {
|
|
1891
3022
|
nativeThreadId: threadId,
|
|
1892
3023
|
providerPid,
|
|
3024
|
+
userAgent,
|
|
1893
3025
|
threadContext,
|
|
1894
3026
|
startTurn,
|
|
3027
|
+
async respond(interactionId, reply) {
|
|
3028
|
+
ensureAlive();
|
|
3029
|
+
answerCodexSessionRequest({ turn: current, externalPending, interactionId, reply });
|
|
3030
|
+
},
|
|
1895
3031
|
...controlClient,
|
|
3032
|
+
...bindCodexSessionThreadControls(controlClient, threadId),
|
|
1896
3033
|
...mutators,
|
|
1897
3034
|
async close() {
|
|
1898
3035
|
await stop();
|
|
1899
3036
|
}
|
|
1900
3037
|
};
|
|
1901
3038
|
}
|
|
3039
|
+
async function openCodexControlConnection(config, input) {
|
|
3040
|
+
const profile = engineProfile("codex", input.profile);
|
|
3041
|
+
const linked = sessionAbort(input.signal);
|
|
3042
|
+
const externalPending = new Map;
|
|
3043
|
+
let dead;
|
|
3044
|
+
let opened = false;
|
|
3045
|
+
let closing = false;
|
|
3046
|
+
let connected;
|
|
3047
|
+
try {
|
|
3048
|
+
connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
|
|
3049
|
+
profileId: profile.profileId,
|
|
3050
|
+
limits: config.limits,
|
|
3051
|
+
externalPending,
|
|
3052
|
+
getTurn: () => {
|
|
3053
|
+
return;
|
|
3054
|
+
},
|
|
3055
|
+
clearTurn: () => {
|
|
3056
|
+
return;
|
|
3057
|
+
},
|
|
3058
|
+
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3059
|
+
...config.onServerRequest !== undefined && {
|
|
3060
|
+
onServerRequest: config.onServerRequest
|
|
3061
|
+
},
|
|
3062
|
+
...config.serverRequestDelivery !== undefined && {
|
|
3063
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
3064
|
+
}
|
|
3065
|
+
}), (error) => {
|
|
3066
|
+
const shouldNotify = opened && !closing && input.signal?.aborted !== true;
|
|
3067
|
+
dead = error;
|
|
3068
|
+
externalPending.clear();
|
|
3069
|
+
linked.abort();
|
|
3070
|
+
if (shouldNotify)
|
|
3071
|
+
invokeSafely(() => config.onDisconnect?.(error));
|
|
3072
|
+
}, input.onStartupPhase);
|
|
3073
|
+
} catch (error) {
|
|
3074
|
+
linked.release();
|
|
3075
|
+
throw error;
|
|
3076
|
+
}
|
|
3077
|
+
if (dead !== undefined || linked.signal.aborted) {
|
|
3078
|
+
const reason = dead ?? abortReason(linked.signal);
|
|
3079
|
+
closing = true;
|
|
3080
|
+
externalPending.clear();
|
|
3081
|
+
try {
|
|
3082
|
+
await stopConnection(connected, { error: reason });
|
|
3083
|
+
} finally {
|
|
3084
|
+
linked.abort();
|
|
3085
|
+
linked.release();
|
|
3086
|
+
}
|
|
3087
|
+
throw reason;
|
|
3088
|
+
}
|
|
3089
|
+
const ensureAlive = () => {
|
|
3090
|
+
if (closing)
|
|
3091
|
+
throw new Error("The Codex control connection is closed");
|
|
3092
|
+
if (dead !== undefined)
|
|
3093
|
+
throw dead;
|
|
3094
|
+
};
|
|
3095
|
+
const controlClient = createCodexControlClient({
|
|
3096
|
+
peer: connected.peer,
|
|
3097
|
+
imageOptions: config,
|
|
3098
|
+
signal: linked.signal,
|
|
3099
|
+
ensureAlive
|
|
3100
|
+
});
|
|
3101
|
+
opened = true;
|
|
3102
|
+
return {
|
|
3103
|
+
providerPid: connected.providerPid,
|
|
3104
|
+
userAgent: connected.userAgent,
|
|
3105
|
+
...controlClient,
|
|
3106
|
+
async respond(interactionId, reply) {
|
|
3107
|
+
ensureAlive();
|
|
3108
|
+
answerCodexSessionRequest({ turn: undefined, externalPending, interactionId, reply });
|
|
3109
|
+
},
|
|
3110
|
+
async close() {
|
|
3111
|
+
closing = true;
|
|
3112
|
+
externalPending.clear();
|
|
3113
|
+
try {
|
|
3114
|
+
await stopConnection(connected);
|
|
3115
|
+
} finally {
|
|
3116
|
+
linked.abort();
|
|
3117
|
+
linked.release();
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
};
|
|
3121
|
+
}
|
|
3122
|
+
|
|
3123
|
+
// src/agent-executor/codex/shared-thread.ts
|
|
3124
|
+
var CLOSE_UNSUBSCRIBE_TIMEOUT_MS = 5000;
|
|
3125
|
+
function bestEffortUnsubscribe(state, threadId) {
|
|
3126
|
+
if (state.isServerClosing() || state.getServerDead() !== undefined) {
|
|
3127
|
+
return Promise.resolve();
|
|
3128
|
+
}
|
|
3129
|
+
return state.peer.request("thread/unsubscribe", { threadId }, { timeoutMs: CLOSE_UNSUBSCRIBE_TIMEOUT_MS }).then(() => {
|
|
3130
|
+
return;
|
|
3131
|
+
}, () => {
|
|
3132
|
+
return;
|
|
3133
|
+
});
|
|
3134
|
+
}
|
|
3135
|
+
function buildSharedThreadSession(params) {
|
|
3136
|
+
const { state, slot, threadContext, activeModelProvider, threadAbort } = params;
|
|
3137
|
+
const { threadId } = slot;
|
|
3138
|
+
const ensureThreadAlive = () => {
|
|
3139
|
+
if (slot.closed)
|
|
3140
|
+
throw new Error("The Codex session is closed");
|
|
3141
|
+
if (slot.dead !== undefined)
|
|
3142
|
+
throw slot.dead;
|
|
3143
|
+
state.ensureServerAlive();
|
|
3144
|
+
};
|
|
3145
|
+
const threadControlClient = createCodexControlClient({
|
|
3146
|
+
peer: state.peer,
|
|
3147
|
+
imageOptions: state.config,
|
|
3148
|
+
signal: threadAbort.signal,
|
|
3149
|
+
ensureAlive: ensureThreadAlive,
|
|
3150
|
+
onBeforeInterruptTurn: state.onBeforeInterruptTurn
|
|
3151
|
+
});
|
|
3152
|
+
const startTurn = createCodexStartTurn({
|
|
3153
|
+
config: state.config,
|
|
3154
|
+
peer: state.peer,
|
|
3155
|
+
threadId,
|
|
3156
|
+
activeModelProvider,
|
|
3157
|
+
signal: threadAbort.signal,
|
|
3158
|
+
ensureAlive: ensureThreadAlive,
|
|
3159
|
+
getTurn: () => slot.current,
|
|
3160
|
+
setTurn: (turn) => {
|
|
3161
|
+
slot.current = turn;
|
|
3162
|
+
}
|
|
3163
|
+
});
|
|
3164
|
+
const mutators = createCodexSessionMutators({
|
|
3165
|
+
peer: state.peer,
|
|
3166
|
+
threadId,
|
|
3167
|
+
imageOptions: state.config,
|
|
3168
|
+
signal: threadAbort.signal,
|
|
3169
|
+
ensureAlive: ensureThreadAlive,
|
|
3170
|
+
getActiveTurn: () => slot.current
|
|
3171
|
+
});
|
|
3172
|
+
const closeThread = async () => {
|
|
3173
|
+
if (slot.closed)
|
|
3174
|
+
return;
|
|
3175
|
+
slot.closed = true;
|
|
3176
|
+
const turn = slot.current;
|
|
3177
|
+
slot.current = undefined;
|
|
3178
|
+
slot.externalPending.clear();
|
|
3179
|
+
loseEngineTurn(turn, codexStopped, new Error("The Codex session closed"));
|
|
3180
|
+
state.threads.delete(threadId);
|
|
3181
|
+
try {
|
|
3182
|
+
await bestEffortUnsubscribe(state, threadId);
|
|
3183
|
+
} finally {
|
|
3184
|
+
threadAbort.abort();
|
|
3185
|
+
slot.releaseThreadSignal();
|
|
3186
|
+
}
|
|
3187
|
+
};
|
|
3188
|
+
threadAbort.signal.addEventListener("abort", () => {
|
|
3189
|
+
if (slot.closed)
|
|
3190
|
+
return;
|
|
3191
|
+
slot.closed = true;
|
|
3192
|
+
const reason = abortReason(threadAbort.signal);
|
|
3193
|
+
slot.dead = slot.dead ?? (reason instanceof Error ? reason : new Error(String(reason)));
|
|
3194
|
+
const turn = slot.current;
|
|
3195
|
+
slot.current = undefined;
|
|
3196
|
+
slot.externalPending.clear();
|
|
3197
|
+
loseEngineTurn(turn, codexStopped, slot.dead);
|
|
3198
|
+
state.threads.delete(threadId);
|
|
3199
|
+
slot.releaseThreadSignal();
|
|
3200
|
+
bestEffortUnsubscribe(state, threadId);
|
|
3201
|
+
}, { once: true });
|
|
3202
|
+
return {
|
|
3203
|
+
nativeThreadId: threadId,
|
|
3204
|
+
providerPid: state.providerPid,
|
|
3205
|
+
userAgent: state.userAgent,
|
|
3206
|
+
threadContext,
|
|
3207
|
+
startTurn,
|
|
3208
|
+
async respond(interactionId, reply) {
|
|
3209
|
+
ensureThreadAlive();
|
|
3210
|
+
answerCodexSessionRequest({
|
|
3211
|
+
turn: slot.current,
|
|
3212
|
+
externalPending: slot.externalPending,
|
|
3213
|
+
interactionId,
|
|
3214
|
+
reply
|
|
3215
|
+
});
|
|
3216
|
+
},
|
|
3217
|
+
...threadControlClient,
|
|
3218
|
+
...bindCodexSessionThreadControls(threadControlClient, threadId),
|
|
3219
|
+
...mutators,
|
|
3220
|
+
close: closeThread
|
|
3221
|
+
};
|
|
3222
|
+
}
|
|
3223
|
+
async function openSharedCodexThread(state, threadInput) {
|
|
3224
|
+
state.ensureServerAlive();
|
|
3225
|
+
validateCodexOpenInput({ ...threadInput, profile: state.profile });
|
|
3226
|
+
if (threadInput.nativeThreadId !== undefined && (state.threads.has(threadInput.nativeThreadId) || state.openingNativeThreadIds.has(threadInput.nativeThreadId))) {
|
|
3227
|
+
throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadInput.nativeThreadId} is already open on this shared server`);
|
|
3228
|
+
}
|
|
3229
|
+
if (state.threads.size + state.openingThreads >= state.maxThreads) {
|
|
3230
|
+
throw new RangeError(`[stitchkit] CodexSharedServer.openThread: active thread limit (${state.maxThreads}) reached`);
|
|
3231
|
+
}
|
|
3232
|
+
const threadAbort = sessionAbort(threadInput.signal);
|
|
3233
|
+
const onServerAbort = () => threadAbort.abort();
|
|
3234
|
+
state.serverSignal.addEventListener("abort", onServerAbort, { once: true });
|
|
3235
|
+
let signalReleased = false;
|
|
3236
|
+
const releaseThreadSignal = () => {
|
|
3237
|
+
if (signalReleased)
|
|
3238
|
+
return;
|
|
3239
|
+
signalReleased = true;
|
|
3240
|
+
state.serverSignal.removeEventListener("abort", onServerAbort);
|
|
3241
|
+
threadAbort.release();
|
|
3242
|
+
};
|
|
3243
|
+
state.openingThreads += 1;
|
|
3244
|
+
if (threadInput.nativeThreadId !== undefined) {
|
|
3245
|
+
state.openingNativeThreadIds.add(threadInput.nativeThreadId);
|
|
3246
|
+
}
|
|
3247
|
+
let registeredThreadId;
|
|
3248
|
+
const openControls = createCodexControlClient({
|
|
3249
|
+
peer: state.peer,
|
|
3250
|
+
imageOptions: state.config,
|
|
3251
|
+
signal: threadAbort.signal,
|
|
3252
|
+
ensureAlive: () => {
|
|
3253
|
+
threadAbort.signal.throwIfAborted();
|
|
3254
|
+
state.ensureServerAlive();
|
|
3255
|
+
},
|
|
3256
|
+
onBeforeInterruptTurn: state.onBeforeInterruptTurn
|
|
3257
|
+
});
|
|
3258
|
+
try {
|
|
3259
|
+
threadAbort.signal.throwIfAborted();
|
|
3260
|
+
let dynamicOverrides;
|
|
3261
|
+
if (state.config.prepareThread !== undefined) {
|
|
3262
|
+
dynamicOverrides = await raceAbort(Promise.resolve(state.config.prepareThread({
|
|
3263
|
+
controls: openControls,
|
|
3264
|
+
cwd: threadInput.cwd,
|
|
3265
|
+
...threadInput.nativeThreadId !== undefined && {
|
|
3266
|
+
nativeThreadId: threadInput.nativeThreadId
|
|
3267
|
+
},
|
|
3268
|
+
...threadInput.forkFrom !== undefined && { forkFrom: threadInput.forkFrom }
|
|
3269
|
+
})), threadAbort.signal);
|
|
3270
|
+
threadAbort.signal.throwIfAborted();
|
|
3271
|
+
state.ensureServerAlive();
|
|
3272
|
+
}
|
|
3273
|
+
const disposeLateOpen = (reply) => {
|
|
3274
|
+
const parsedLate = CodexStartedThreadSchema.safeParse(reply);
|
|
3275
|
+
if (parsedLate.success && !state.threads.has(parsedLate.data.thread.id)) {
|
|
3276
|
+
bestEffortUnsubscribe(state, parsedLate.data.thread.id);
|
|
3277
|
+
}
|
|
3278
|
+
};
|
|
3279
|
+
const openedReply = await raceAbort(openCodexThreadRpc(state.peer, state.config, threadInput, dynamicOverrides), threadAbort.signal, disposeLateOpen);
|
|
3280
|
+
threadAbort.signal.throwIfAborted();
|
|
3281
|
+
state.ensureServerAlive();
|
|
3282
|
+
const parsed = CodexStartedThreadSchema.parse(openedReply);
|
|
3283
|
+
const threadId = parsed.thread.id;
|
|
3284
|
+
const threadContext = extractCodexThreadContext(parsed);
|
|
3285
|
+
if (state.threads.has(threadId)) {
|
|
3286
|
+
throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadId} is already open on this shared server`);
|
|
3287
|
+
}
|
|
3288
|
+
const externalPending = new Map;
|
|
3289
|
+
const slot = {
|
|
3290
|
+
threadId,
|
|
3291
|
+
current: undefined,
|
|
3292
|
+
externalPending,
|
|
3293
|
+
closed: false,
|
|
3294
|
+
dead: undefined,
|
|
3295
|
+
abortThread: () => threadAbort.abort(),
|
|
3296
|
+
releaseThreadSignal,
|
|
3297
|
+
handlers: createCodexHandlers({
|
|
3298
|
+
profileId: state.profile.profileId,
|
|
3299
|
+
limits: state.config.limits,
|
|
3300
|
+
externalPending,
|
|
3301
|
+
getTurn: () => slot.current,
|
|
3302
|
+
clearTurn: () => {
|
|
3303
|
+
slot.current = undefined;
|
|
3304
|
+
},
|
|
3305
|
+
...state.config.onNotification !== undefined && {
|
|
3306
|
+
onNotification: state.config.onNotification
|
|
3307
|
+
},
|
|
3308
|
+
...state.config.onServerRequest !== undefined && {
|
|
3309
|
+
onServerRequest: state.config.onServerRequest
|
|
3310
|
+
},
|
|
3311
|
+
...state.config.serverRequestDelivery !== undefined && {
|
|
3312
|
+
serverRequestDelivery: state.config.serverRequestDelivery
|
|
3313
|
+
}
|
|
3314
|
+
})
|
|
3315
|
+
};
|
|
3316
|
+
state.threads.set(threadId, slot);
|
|
3317
|
+
registeredThreadId = threadId;
|
|
3318
|
+
if (state.config.verifyThread !== undefined) {
|
|
3319
|
+
emitStartupPhase(threadInput.onStartupPhase, "verifying");
|
|
3320
|
+
await raceAbort(Promise.resolve(state.config.verifyThread({
|
|
3321
|
+
nativeThreadId: threadId,
|
|
3322
|
+
threadContext,
|
|
3323
|
+
controls: openControls
|
|
3324
|
+
})), threadAbort.signal);
|
|
3325
|
+
threadAbort.signal.throwIfAborted();
|
|
3326
|
+
}
|
|
3327
|
+
state.ensureServerAlive();
|
|
3328
|
+
threadAbort.signal.throwIfAborted();
|
|
3329
|
+
if (slot.dead !== undefined)
|
|
3330
|
+
throw slot.dead;
|
|
3331
|
+
const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? threadInput.forkFrom?.modelProvider ?? state.config.modelProvider;
|
|
3332
|
+
return buildSharedThreadSession({
|
|
3333
|
+
state,
|
|
3334
|
+
slot,
|
|
3335
|
+
threadContext,
|
|
3336
|
+
activeModelProvider,
|
|
3337
|
+
threadAbort
|
|
3338
|
+
});
|
|
3339
|
+
} catch (error) {
|
|
3340
|
+
if (registeredThreadId !== undefined) {
|
|
3341
|
+
state.threads.delete(registeredThreadId);
|
|
3342
|
+
await bestEffortUnsubscribe(state, registeredThreadId);
|
|
3343
|
+
}
|
|
3344
|
+
threadAbort.abort();
|
|
3345
|
+
releaseThreadSignal();
|
|
3346
|
+
throw error;
|
|
3347
|
+
} finally {
|
|
3348
|
+
state.openingThreads -= 1;
|
|
3349
|
+
if (threadInput.nativeThreadId !== undefined) {
|
|
3350
|
+
state.openingNativeThreadIds.delete(threadInput.nativeThreadId);
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
|
|
3355
|
+
// src/agent-executor/codex/shared-server.ts
|
|
3356
|
+
var DEFAULT_MAX_SHARED_THREADS = 32;
|
|
3357
|
+
var HARD_MAX_SHARED_THREADS = 256;
|
|
3358
|
+
function extractCodexThreadId(params) {
|
|
3359
|
+
if (!isRecord(params))
|
|
3360
|
+
return;
|
|
3361
|
+
if (typeof params.threadId === "string" && params.threadId.length > 0)
|
|
3362
|
+
return params.threadId;
|
|
3363
|
+
if (isRecord(params.thread) && typeof params.thread.id === "string" && params.thread.id.length > 0) {
|
|
3364
|
+
return params.thread.id;
|
|
3365
|
+
}
|
|
3366
|
+
if (isRecord(params.turn) && typeof params.turn.threadId === "string" && params.turn.threadId.length > 0) {
|
|
3367
|
+
return params.turn.threadId;
|
|
3368
|
+
}
|
|
3369
|
+
return;
|
|
3370
|
+
}
|
|
3371
|
+
function validateSharedServerInputs(config, input) {
|
|
3372
|
+
if (config.transport !== undefined && config.transport.kind !== "stdio") {
|
|
3373
|
+
throw new TypeError(`[stitchkit] CodexDriver.openSharedServer: shared multi-thread mode requires stdio transport (received ${JSON.stringify(config.transport.kind)})`);
|
|
3374
|
+
}
|
|
3375
|
+
const maxThreads = input.maxThreads ?? DEFAULT_MAX_SHARED_THREADS;
|
|
3376
|
+
assertPositiveSafeInteger("[stitchkit] CodexDriver.openSharedServer: maxThreads", maxThreads);
|
|
3377
|
+
if (maxThreads > HARD_MAX_SHARED_THREADS) {
|
|
3378
|
+
throw new RangeError(`[stitchkit] CodexDriver.openSharedServer: maxThreads (${maxThreads}) must not exceed ${HARD_MAX_SHARED_THREADS}`);
|
|
3379
|
+
}
|
|
3380
|
+
return maxThreads;
|
|
3381
|
+
}
|
|
3382
|
+
async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
3383
|
+
const maxThreads = validateSharedServerInputs(config, input);
|
|
3384
|
+
const profile = engineProfile("codex", input.profile);
|
|
3385
|
+
const linked = sessionAbort(input.signal);
|
|
3386
|
+
const threads = new Map;
|
|
3387
|
+
const globalExternalPending = new Map;
|
|
3388
|
+
let serverDead;
|
|
3389
|
+
let serverClosing = false;
|
|
3390
|
+
let opened = false;
|
|
3391
|
+
const globalHandlers = createCodexHandlers({
|
|
3392
|
+
profileId: profile.profileId,
|
|
3393
|
+
limits: config.limits,
|
|
3394
|
+
externalPending: globalExternalPending,
|
|
3395
|
+
getTurn: () => {
|
|
3396
|
+
return;
|
|
3397
|
+
},
|
|
3398
|
+
clearTurn: () => {
|
|
3399
|
+
return;
|
|
3400
|
+
},
|
|
3401
|
+
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3402
|
+
...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
|
|
3403
|
+
...config.serverRequestDelivery !== undefined && {
|
|
3404
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
3405
|
+
}
|
|
3406
|
+
});
|
|
3407
|
+
const failAllThreads = (error) => {
|
|
3408
|
+
for (const slot of [...threads.values()]) {
|
|
3409
|
+
slot.closed = true;
|
|
3410
|
+
slot.dead = error;
|
|
3411
|
+
const turn = slot.current;
|
|
3412
|
+
slot.current = undefined;
|
|
3413
|
+
slot.externalPending.clear();
|
|
3414
|
+
loseEngineTurn(turn, codexStopped, error);
|
|
3415
|
+
slot.abortThread();
|
|
3416
|
+
slot.releaseThreadSignal();
|
|
3417
|
+
}
|
|
3418
|
+
threads.clear();
|
|
3419
|
+
};
|
|
3420
|
+
let connected;
|
|
3421
|
+
try {
|
|
3422
|
+
connected = await connectCodex(config, profile, input.cwd, linked.signal, {
|
|
3423
|
+
onNotification(method, params) {
|
|
3424
|
+
if (method === "account/rateLimits/updated") {
|
|
3425
|
+
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3426
|
+
return;
|
|
3427
|
+
}
|
|
3428
|
+
const targetId = extractCodexThreadId(params);
|
|
3429
|
+
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3430
|
+
if (slot !== undefined) {
|
|
3431
|
+
invokeSafely(() => slot.handlers.onNotification(method, params));
|
|
3432
|
+
return;
|
|
3433
|
+
}
|
|
3434
|
+
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3435
|
+
},
|
|
3436
|
+
onRequest(method, params, id) {
|
|
3437
|
+
const targetId = extractCodexThreadId(params);
|
|
3438
|
+
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3439
|
+
if (slot !== undefined)
|
|
3440
|
+
return slot.handlers.onRequest(method, params, id);
|
|
3441
|
+
return globalHandlers.onRequest(method, params, id);
|
|
3442
|
+
}
|
|
3443
|
+
}, (error) => {
|
|
3444
|
+
const shouldNotify = opened && !serverClosing && input.signal?.aborted !== true;
|
|
3445
|
+
serverDead = error;
|
|
3446
|
+
globalExternalPending.clear();
|
|
3447
|
+
failAllThreads(error);
|
|
3448
|
+
linked.abort();
|
|
3449
|
+
if (shouldNotify)
|
|
3450
|
+
invokeSafely(() => config.onDisconnect?.(error));
|
|
3451
|
+
}, input.onStartupPhase);
|
|
3452
|
+
} catch (error) {
|
|
3453
|
+
linked.release();
|
|
3454
|
+
throw error;
|
|
3455
|
+
}
|
|
3456
|
+
const { peer, providerPid, userAgent } = connected;
|
|
3457
|
+
const ensureServerAlive = () => {
|
|
3458
|
+
if (serverClosing)
|
|
3459
|
+
throw new Error("The Codex shared server is closed");
|
|
3460
|
+
if (serverDead !== undefined)
|
|
3461
|
+
throw serverDead;
|
|
3462
|
+
};
|
|
3463
|
+
const onBeforeInterruptTurn = (targetThreadId, turnId) => {
|
|
3464
|
+
interruptLocalCodexTurn(threads.get(targetThreadId)?.current, turnId);
|
|
3465
|
+
};
|
|
3466
|
+
const controlClient = createCodexControlClient({
|
|
3467
|
+
peer,
|
|
3468
|
+
imageOptions: config,
|
|
3469
|
+
signal: linked.signal,
|
|
3470
|
+
ensureAlive: ensureServerAlive,
|
|
3471
|
+
onBeforeInterruptTurn
|
|
3472
|
+
});
|
|
3473
|
+
const sharedCapabilities = {
|
|
3474
|
+
...baseCapabilities,
|
|
3475
|
+
multiThreadPerProcess: true
|
|
3476
|
+
};
|
|
3477
|
+
const state = {
|
|
3478
|
+
config,
|
|
3479
|
+
profile,
|
|
3480
|
+
peer,
|
|
3481
|
+
providerPid,
|
|
3482
|
+
userAgent,
|
|
3483
|
+
maxThreads,
|
|
3484
|
+
onBeforeInterruptTurn,
|
|
3485
|
+
serverSignal: linked.signal,
|
|
3486
|
+
threads,
|
|
3487
|
+
openingNativeThreadIds: new Set,
|
|
3488
|
+
openingThreads: 0,
|
|
3489
|
+
isServerClosing: () => serverClosing,
|
|
3490
|
+
getServerDead: () => serverDead,
|
|
3491
|
+
ensureServerAlive
|
|
3492
|
+
};
|
|
3493
|
+
const closeServer = async () => {
|
|
3494
|
+
if (serverClosing)
|
|
3495
|
+
return;
|
|
3496
|
+
serverClosing = true;
|
|
3497
|
+
globalExternalPending.clear();
|
|
3498
|
+
failAllThreads(new Error("The Codex shared server closed"));
|
|
3499
|
+
try {
|
|
3500
|
+
await stopConnection(connected);
|
|
3501
|
+
} finally {
|
|
3502
|
+
linked.abort();
|
|
3503
|
+
linked.release();
|
|
3504
|
+
}
|
|
3505
|
+
};
|
|
3506
|
+
opened = true;
|
|
3507
|
+
return {
|
|
3508
|
+
providerPid,
|
|
3509
|
+
userAgent,
|
|
3510
|
+
maxThreads,
|
|
3511
|
+
get activeThreadCount() {
|
|
3512
|
+
return threads.size;
|
|
3513
|
+
},
|
|
3514
|
+
capabilities: sharedCapabilities,
|
|
3515
|
+
...controlClient,
|
|
3516
|
+
openThread: (threadInput) => openSharedCodexThread(state, threadInput),
|
|
3517
|
+
close: closeServer
|
|
3518
|
+
};
|
|
3519
|
+
}
|
|
1902
3520
|
|
|
1903
3521
|
// src/agent-executor/codex/driver.ts
|
|
1904
3522
|
var MAX_HISTORY_PAGES = 256;
|
|
1905
3523
|
var FIND_INPUT_MAX_LINE_BYTES = 64 * 1024 * 1024;
|
|
1906
|
-
function
|
|
3524
|
+
async function findCodexClientInput(peer, nativeThreadId, clientId) {
|
|
3525
|
+
const seen = new Set;
|
|
3526
|
+
let cursor;
|
|
3527
|
+
for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
|
|
3528
|
+
const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
|
|
3529
|
+
threadId: nativeThreadId,
|
|
3530
|
+
limit: 50,
|
|
3531
|
+
itemsView: "full",
|
|
3532
|
+
...cursor !== undefined && { cursor }
|
|
3533
|
+
}));
|
|
3534
|
+
if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId))) {
|
|
3535
|
+
return true;
|
|
3536
|
+
}
|
|
3537
|
+
const next = page.nextCursor;
|
|
3538
|
+
if (next === null || next === undefined)
|
|
3539
|
+
return false;
|
|
3540
|
+
if (seen.has(next)) {
|
|
3541
|
+
throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
3542
|
+
}
|
|
3543
|
+
seen.add(next);
|
|
3544
|
+
cursor = next;
|
|
3545
|
+
}
|
|
3546
|
+
throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
|
|
3547
|
+
}
|
|
3548
|
+
function validateCodexDriverOptions(config) {
|
|
1907
3549
|
validateImageOptions(config);
|
|
3550
|
+
assertPositiveSafeInteger("maxFrameBytes", config.maxFrameBytes);
|
|
1908
3551
|
validateCodexTransportAndArgs(config);
|
|
1909
3552
|
validateCodexPolicyOverrides(config, "createCodexDriver");
|
|
3553
|
+
if (config.serverRequestDelivery !== undefined && config.serverRequestDelivery !== "external-only" && config.serverRequestDelivery !== "all") {
|
|
3554
|
+
throw new TypeError(`[stitchkit] createCodexDriver: serverRequestDelivery must be "external-only" or "all", received ${JSON.stringify(config.serverRequestDelivery)}`);
|
|
3555
|
+
}
|
|
3556
|
+
if (config.serverRequestDelivery === "all" && config.onServerRequest === undefined) {
|
|
3557
|
+
throw new TypeError('[stitchkit] createCodexDriver: serverRequestDelivery "all" requires onServerRequest');
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
function buildCodexSessionConfig(input) {
|
|
3561
|
+
const { config } = input;
|
|
3562
|
+
const transport = input.forceStdioForListen && config.transport?.kind === "unix-listen" ? { kind: "stdio" } : config.transport;
|
|
3563
|
+
const maxFrameBytes = input.maxFrameBytes ?? config.maxFrameBytes;
|
|
3564
|
+
return {
|
|
3565
|
+
executable: input.executable,
|
|
3566
|
+
prefix: input.prefix,
|
|
3567
|
+
...transport !== undefined && { transport },
|
|
3568
|
+
...config.serverArgs !== undefined && { serverArgs: config.serverArgs },
|
|
3569
|
+
...config.model !== undefined && { model: config.model },
|
|
3570
|
+
...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
|
|
3571
|
+
approvalPolicy: config.approvalPolicy ?? "on-request",
|
|
3572
|
+
sandbox: config.sandbox ?? "workspace-write",
|
|
3573
|
+
...config.developerInstructions !== undefined && {
|
|
3574
|
+
developerInstructions: config.developerInstructions
|
|
3575
|
+
},
|
|
3576
|
+
...config.runtimeWorkspaceRoots !== undefined && {
|
|
3577
|
+
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
3578
|
+
},
|
|
3579
|
+
...config.config !== undefined && { config: config.config },
|
|
3580
|
+
...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
|
|
3581
|
+
...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
|
|
3582
|
+
...!input.ephemeralProbe && config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3583
|
+
...!input.ephemeralProbe && config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
|
|
3584
|
+
...!input.ephemeralProbe && config.serverRequestDelivery !== undefined && {
|
|
3585
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
3586
|
+
},
|
|
3587
|
+
...!input.ephemeralProbe && config.onDisconnect !== undefined && { onDisconnect: config.onDisconnect },
|
|
3588
|
+
ambient: input.ambient,
|
|
3589
|
+
limits: input.limits,
|
|
3590
|
+
version: input.version,
|
|
3591
|
+
...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
|
|
3592
|
+
...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
|
|
3593
|
+
...maxFrameBytes !== undefined && { maxFrameBytes }
|
|
3594
|
+
};
|
|
3595
|
+
}
|
|
3596
|
+
function createCodexDriver(config = {}) {
|
|
3597
|
+
validateCodexDriverOptions(config);
|
|
1910
3598
|
const executable = config.executable ?? "codex";
|
|
1911
3599
|
const prefix = config.prefixArgs ?? [];
|
|
1912
3600
|
const ambient = config.ambient ?? process.env;
|
|
1913
3601
|
const limits = new Map;
|
|
1914
3602
|
let version = "unknown";
|
|
1915
|
-
const
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
1931
|
-
},
|
|
1932
|
-
...config.config !== undefined && { config: config.config },
|
|
1933
|
-
...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
|
|
1934
|
-
...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
|
|
1935
|
-
ambient,
|
|
1936
|
-
limits,
|
|
1937
|
-
version,
|
|
1938
|
-
...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
|
|
1939
|
-
...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
|
|
1940
|
-
...options?.maxLineBytes !== undefined && { maxLineBytes: options.maxLineBytes }
|
|
1941
|
-
};
|
|
3603
|
+
const capabilities = {
|
|
3604
|
+
runtimePolicyEnforcement: "native",
|
|
3605
|
+
sessionApproval: true,
|
|
3606
|
+
interruptOnDeny: true,
|
|
3607
|
+
updatedToolInput: false,
|
|
3608
|
+
structuredInput: true,
|
|
3609
|
+
steer: true,
|
|
3610
|
+
fork: true,
|
|
3611
|
+
revert: true,
|
|
3612
|
+
compact: true,
|
|
3613
|
+
injectItems: true,
|
|
3614
|
+
backgroundWorkOutlivesTurn: false,
|
|
3615
|
+
multiThreadPerProcess: false,
|
|
3616
|
+
images: config.resolveFile !== undefined,
|
|
3617
|
+
planLimits: "pull"
|
|
1942
3618
|
};
|
|
3619
|
+
const session = (options) => buildCodexSessionConfig({
|
|
3620
|
+
config,
|
|
3621
|
+
executable,
|
|
3622
|
+
prefix,
|
|
3623
|
+
ambient,
|
|
3624
|
+
limits,
|
|
3625
|
+
version,
|
|
3626
|
+
...options
|
|
3627
|
+
});
|
|
1943
3628
|
const cli = (profile, args) => runEngineCli({ executable, prefix, args, profile, ambient });
|
|
1944
|
-
const ask = (profile, cwd, question,
|
|
1945
|
-
...
|
|
1946
|
-
forceStdioForListen: true
|
|
3629
|
+
const ask = (profile, cwd, question, maxFrameBytes) => withEphemeralConnection((signal) => connectCodex(session({
|
|
3630
|
+
...maxFrameBytes !== undefined && { maxFrameBytes },
|
|
3631
|
+
forceStdioForListen: true,
|
|
3632
|
+
ephemeralProbe: true
|
|
1947
3633
|
}), engineProfile("codex", profile), cwd, signal), (connection) => question(connection.peer));
|
|
1948
3634
|
return {
|
|
1949
3635
|
engine: "codex",
|
|
1950
3636
|
reconcile: "client-id",
|
|
3637
|
+
capabilities,
|
|
1951
3638
|
async info() {
|
|
1952
3639
|
const probe = {
|
|
1953
3640
|
profileId: "version-probe",
|
|
@@ -1961,7 +3648,8 @@ function createCodexDriver(config = {}) {
|
|
|
1961
3648
|
engine: "codex",
|
|
1962
3649
|
version,
|
|
1963
3650
|
reconcile: "client-id",
|
|
1964
|
-
models: { answer: "not-asked" }
|
|
3651
|
+
models: { answer: "not-asked" },
|
|
3652
|
+
capabilities
|
|
1965
3653
|
};
|
|
1966
3654
|
},
|
|
1967
3655
|
async status(profile) {
|
|
@@ -2000,32 +3688,11 @@ ${decoder.decode(loginResult.stderr)}`.trim();
|
|
|
2000
3688
|
};
|
|
2001
3689
|
},
|
|
2002
3690
|
async findInput(input) {
|
|
2003
|
-
return ask(input.profile, input.cwd,
|
|
2004
|
-
const seen = new Set;
|
|
2005
|
-
let cursor;
|
|
2006
|
-
for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
|
|
2007
|
-
const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
|
|
2008
|
-
threadId: input.nativeThreadId,
|
|
2009
|
-
limit: 50,
|
|
2010
|
-
itemsView: "full",
|
|
2011
|
-
...cursor !== undefined && { cursor }
|
|
2012
|
-
}));
|
|
2013
|
-
if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === input.clientId))) {
|
|
2014
|
-
return true;
|
|
2015
|
-
}
|
|
2016
|
-
const next = page.nextCursor;
|
|
2017
|
-
if (next === null || next === undefined)
|
|
2018
|
-
return false;
|
|
2019
|
-
if (seen.has(next)) {
|
|
2020
|
-
throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
2021
|
-
}
|
|
2022
|
-
seen.add(next);
|
|
2023
|
-
cursor = next;
|
|
2024
|
-
}
|
|
2025
|
-
throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
|
|
2026
|
-
}, FIND_INPUT_MAX_LINE_BYTES);
|
|
3691
|
+
return ask(input.profile, input.cwd, (peer) => findCodexClientInput(peer, input.nativeThreadId, input.clientId), Math.max(FIND_INPUT_MAX_LINE_BYTES, config.maxFrameBytes ?? 0));
|
|
2027
3692
|
},
|
|
2028
|
-
open: (input) => openCodexSession(session(), input)
|
|
3693
|
+
open: (input) => openCodexSession(session(), input),
|
|
3694
|
+
connectControl: (input) => openCodexControlConnection(session(), input),
|
|
3695
|
+
openSharedServer: (input) => openCodexSharedServer(session(), capabilities, input)
|
|
2029
3696
|
};
|
|
2030
3697
|
}
|
|
2031
3698
|
// src/agent-executor/codex/scenarios.ts
|
|
@@ -2114,6 +3781,8 @@ var codexFakeScenarios = {
|
|
|
2114
3781
|
crash: () => steps(text("dying "), { do: "crash" })
|
|
2115
3782
|
};
|
|
2116
3783
|
export {
|
|
3784
|
+
CodexLocalImageInputSchema,
|
|
3785
|
+
CodexSkillInputSchema,
|
|
2117
3786
|
CodexUnixSocketError,
|
|
2118
3787
|
codexFakeScenarios,
|
|
2119
3788
|
codexPlanWindows,
|