stitchkit 0.130.0 → 0.131.0
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 +48 -0
- package/dist/agent-executor/acp/v1-connect.d.ts +40 -26
- package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-driver.d.ts +10 -4
- package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-handlers.d.ts +6 -2
- package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-probe.d.ts +38 -0
- package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-protocol.d.ts +15 -0
- package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-session.d.ts +9 -7
- package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
- package/dist/agent-executor/claude/cli-driver.d.ts +7 -7
- package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
- package/dist/agent-executor/claude/limits.d.ts +6 -4
- package/dist/agent-executor/claude/limits.d.ts.map +1 -1
- package/dist/agent-executor/claude/session.d.ts +3 -3
- package/dist/agent-executor/claude/session.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/controls.d.ts +1 -0
- package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/driver.d.ts +51 -50
- package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/probe.d.ts +3 -3
- package/dist/agent-executor/claude-sdk/probe.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/query-loop.d.ts +2 -1
- package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
- package/dist/agent-executor/codex/classify.d.ts.map +1 -1
- package/dist/agent-executor/codex/connect.d.ts +9 -7
- package/dist/agent-executor/codex/connect.d.ts.map +1 -1
- package/dist/agent-executor/codex/control-client.d.ts +112 -87
- package/dist/agent-executor/codex/control-client.d.ts.map +1 -1
- package/dist/agent-executor/codex/control-read-methods.d.ts +7 -0
- package/dist/agent-executor/codex/control-read-methods.d.ts.map +1 -0
- package/dist/agent-executor/codex/driver.d.ts +42 -31
- package/dist/agent-executor/codex/driver.d.ts.map +1 -1
- package/dist/agent-executor/codex/event-routing.d.ts +14 -0
- package/dist/agent-executor/codex/event-routing.d.ts.map +1 -0
- package/dist/agent-executor/codex/handlers.d.ts +9 -4
- package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
- package/dist/agent-executor/codex/limits.d.ts +9 -3
- package/dist/agent-executor/codex/limits.d.ts.map +1 -1
- package/dist/agent-executor/codex/notifications.d.ts +183 -0
- package/dist/agent-executor/codex/notifications.d.ts.map +1 -0
- package/dist/agent-executor/codex/pagination.d.ts +54 -0
- package/dist/agent-executor/codex/pagination.d.ts.map +1 -0
- package/dist/agent-executor/codex/protocol.d.ts +586 -144
- package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
- package/dist/agent-executor/codex/request-answers.d.ts +4 -2
- package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
- package/dist/agent-executor/codex/responses.d.ts +855 -0
- package/dist/agent-executor/codex/responses.d.ts.map +1 -0
- package/dist/agent-executor/codex/session-bind.d.ts +410 -0
- package/dist/agent-executor/codex/session-bind.d.ts.map +1 -0
- package/dist/agent-executor/codex/session-controls.d.ts +21 -169
- package/dist/agent-executor/codex/session-controls.d.ts.map +1 -1
- package/dist/agent-executor/codex/session-types.d.ts +190 -0
- package/dist/agent-executor/codex/session-types.d.ts.map +1 -0
- package/dist/agent-executor/codex/session.d.ts +5 -53
- package/dist/agent-executor/codex/session.d.ts.map +1 -1
- package/dist/agent-executor/codex/shared-server.d.ts +7 -5
- package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
- package/dist/agent-executor/codex/shared-thread.d.ts +8 -8
- package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
- package/dist/agent-executor/codex/thread-controls.d.ts +61 -36
- package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -1
- package/dist/agent-executor/codex/thread-list-query.d.ts +5 -0
- package/dist/agent-executor/codex/thread-list-query.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 +25 -7
- package/dist/agent-executor/codex/turn-input.d.ts.map +1 -1
- package/dist/agent-executor/codex/unix-socket-target.d.ts +12 -3
- package/dist/agent-executor/codex/unix-socket-target.d.ts.map +1 -1
- package/dist/agent-executor/codex/ws-frame.d.ts +4 -1
- package/dist/agent-executor/codex/ws-frame.d.ts.map +1 -1
- package/dist/agent-executor/contract.d.ts +3 -1
- package/dist/agent-executor/contract.d.ts.map +1 -1
- package/dist/agent-executor/engine-process.d.ts +4 -4
- package/dist/agent-executor/engine-process.d.ts.map +1 -1
- package/dist/agent-executor/engine.d.ts +3 -3
- package/dist/agent-executor/engine.d.ts.map +1 -1
- package/dist/agent-executor/handoff.d.ts.map +1 -1
- package/dist/agent-executor/hello.d.ts +7 -0
- package/dist/agent-executor/hello.d.ts.map +1 -1
- package/dist/agent-executor/json-rpc-peer.d.ts +9 -4
- package/dist/agent-executor/json-rpc-peer.d.ts.map +1 -1
- package/dist/agent-executor/leases.d.ts +1 -1
- package/dist/agent-executor/leases.d.ts.map +1 -1
- package/dist/agent-executor/plan-limits.d.ts +12 -1
- package/dist/agent-executor/plan-limits.d.ts.map +1 -1
- package/dist/agent-executor/profile.d.ts +7 -0
- package/dist/agent-executor/profile.d.ts.map +1 -1
- package/dist/agent-executor/session-primitives.d.ts +8 -0
- package/dist/agent-executor/session-primitives.d.ts.map +1 -1
- package/dist/agent-executor/testing/consumer-stubs.d.ts +45 -0
- package/dist/agent-executor/testing/consumer-stubs.d.ts.map +1 -0
- package/dist/agent-executor/testing/fake-claude-sdk-query.d.ts +88 -0
- package/dist/agent-executor/testing/fake-claude-sdk-query.d.ts.map +1 -0
- package/dist/agent-executor/testing/fake-codex-app-server.d.ts +56 -0
- package/dist/agent-executor/testing/fake-codex-app-server.d.ts.map +1 -0
- package/dist/agent-executor/testing/fixtures.d.ts +26 -0
- package/dist/agent-executor/testing/fixtures.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-driver.d.ts +8 -8
- package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -1
- package/dist/agent-executor/testing/replay-runner.d.ts +3 -2
- package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -1
- package/dist/agent-executor/testing/replay-transcript.d.ts +5 -3
- package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -1
- package/dist/agent-runtime/branch-observations.d.ts +5 -5
- package/dist/entrypoints/agent-executor/acp.d.ts +2 -1
- package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/acp.js +284 -82
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts +4 -0
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/claude-sdk.js +58 -32
- package/dist/entrypoints/agent-executor/claude.d.ts +2 -2
- package/dist/entrypoints/agent-executor/claude.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/claude.js +25 -20
- package/dist/entrypoints/agent-executor/codex.d.ts +11 -6
- package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/codex.js +2223 -1803
- 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 +880 -18
- package/dist/entrypoints/agent-executor.d.ts +3 -3
- package/dist/entrypoints/agent-executor.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor.js +42 -8
- package/dist/entrypoints/process.js +3 -3
- package/dist/{index-jrn3prgm.js → index-32vaajec.js} +29 -4
- package/dist/{index-p1qmpq0p.js → index-64e9p079.js} +92 -56
- package/dist/{index-dbp6xemn.js → index-g2d9kws8.js} +199 -3
- package/dist/index-gm9yz82v.js +56 -0
- package/dist/index-j15dhkda.js +749 -0
- package/dist/{index-1q0n6zek.js → index-kwsr7j5k.js} +84 -44
- package/llms/agent-executor-acp.txt +5 -5
- package/llms/agent-executor-claude-sdk.txt +3 -1
- package/llms/agent-executor-claude.txt +2 -2
- package/llms/agent-executor-codex.txt +13 -10
- package/llms/agent-executor-testing.txt +5 -1
- package/llms/agent-executor.txt +4 -4
- package/llms/stitchkit.txt +75 -74
- package/llms/{upgrading-0.128.0-0.130.0.txt → upgrading-0.128.0-0.131.0.txt} +56 -3
- package/llms/upgrading.txt +1 -1
- package/llms-full.txt +160 -97
- package/llms.txt +8 -8
- package/package.json +3 -3
- package/dist/index-2s8sy57y.js +0 -229
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import"../../index-2rf33y2h.js";
|
|
2
|
-
import {
|
|
3
|
-
InteractionReplySchema2,
|
|
4
|
-
PlanWindowSchema2,
|
|
5
|
-
engineProfile,
|
|
6
|
-
engineEnvironment2
|
|
7
|
-
} from "../../index-dbp6xemn.js";
|
|
8
1
|
import"../../index-09f7w2qq.js";
|
|
9
2
|
import"../../index-v59pxmf1.js";
|
|
10
3
|
import"../../index-qa2jjb65.js";
|
|
11
4
|
import"../../index-6kec3b14.js";
|
|
5
|
+
import"../../index-2rf33y2h.js";
|
|
12
6
|
import {
|
|
7
|
+
InteractionReplySchema2,
|
|
8
|
+
PlanWindowSchema2,
|
|
9
|
+
PlanLimitsSchema2,
|
|
10
|
+
engineProfile,
|
|
11
|
+
engineEnvironment2,
|
|
12
|
+
TURN_QUEUE,
|
|
13
13
|
nonEmptyString,
|
|
14
|
+
clampPlanName,
|
|
15
|
+
epochMsToIso,
|
|
14
16
|
epochSecondsToIso,
|
|
15
17
|
createTurnDeltaChannel,
|
|
16
18
|
offerTurnDelta,
|
|
@@ -21,26 +23,72 @@ import {
|
|
|
21
23
|
safeJsonValue,
|
|
22
24
|
invokeSafely,
|
|
23
25
|
emitStartupPhase,
|
|
24
|
-
clampUniqueWindowName
|
|
25
|
-
|
|
26
|
-
answerEngineRequest,
|
|
27
|
-
drainEngineRequests,
|
|
28
|
-
endEngineTurn,
|
|
29
|
-
loseEngineTurn
|
|
30
|
-
} from "../../index-2s8sy57y.js";
|
|
31
|
-
import"../../index-673drwkn.js";
|
|
32
|
-
import"../../index-vmbxj75t.js";
|
|
26
|
+
clampUniqueWindowName
|
|
27
|
+
} from "../../index-g2d9kws8.js";
|
|
33
28
|
import {
|
|
29
|
+
JsonRpcValueSchema2,
|
|
34
30
|
JsonRpcError2,
|
|
35
31
|
JSON_RPC_METHOD_NOT_FOUND2,
|
|
36
32
|
createJsonRpcPeer2
|
|
37
|
-
} from "../../index-
|
|
33
|
+
} from "../../index-kwsr7j5k.js";
|
|
34
|
+
import {
|
|
35
|
+
CodexProtocolError2,
|
|
36
|
+
parseCodexResponse,
|
|
37
|
+
unknownTypedRecordSchema,
|
|
38
|
+
CodexApprovalPolicySchema2,
|
|
39
|
+
CodexSandboxModeSchema2,
|
|
40
|
+
CodexSandboxPolicySchema2,
|
|
41
|
+
CodexThreadStatusSchema2,
|
|
42
|
+
CodexTurnStatusSchema2,
|
|
43
|
+
CodexTurnItemsViewSchema2,
|
|
44
|
+
CODEX_THREAD_SOURCE_KINDS2,
|
|
45
|
+
CodexThreadSourceKindSchema2,
|
|
46
|
+
CodexCollaborationModeSchema2,
|
|
47
|
+
CodexThreadItemSchema2,
|
|
48
|
+
CodexTurnSchema,
|
|
49
|
+
CodexListedTurnSchema2,
|
|
50
|
+
CodexTurnsPageSchema2,
|
|
51
|
+
CodexThreadSchema2,
|
|
52
|
+
CodexThreadContextSchema2,
|
|
53
|
+
CodexInitializeResponseSchema,
|
|
54
|
+
CodexStartedThreadSchema,
|
|
55
|
+
extractCodexThreadContext,
|
|
56
|
+
CodexStartedTurnSchema,
|
|
57
|
+
CodexTurnSteerResponseSchema,
|
|
58
|
+
CodexThreadRevertResponseSchema,
|
|
59
|
+
CodexApprovalParamsSchema,
|
|
60
|
+
CodexUserInputParamsSchema,
|
|
61
|
+
CodexUserInputAnswersSchema,
|
|
62
|
+
CodexPermissionsApprovalParamsSchema,
|
|
63
|
+
CodexMcpElicitationParamsSchema,
|
|
64
|
+
CodexMcpElicitationAnswerSchema,
|
|
65
|
+
CODEX_APPROVAL_REQUESTS,
|
|
66
|
+
CODEX_PERMISSIONS_APPROVAL_REQUEST,
|
|
67
|
+
CODEX_INPUT_REQUEST,
|
|
68
|
+
CODEX_ELICITATION_REQUEST,
|
|
69
|
+
CODEX_APPROVAL_DECISION,
|
|
70
|
+
CodexUnixSocketError2,
|
|
71
|
+
validateCodexUnixSocketPath,
|
|
72
|
+
assertCodexUnixListenTargetAvailable,
|
|
73
|
+
assertCodexUnixSocketClientTarget,
|
|
74
|
+
maskedWsFrameByteLength,
|
|
75
|
+
encodeMaskedWsFrame,
|
|
76
|
+
createWsFrameDecoder
|
|
77
|
+
} from "../../index-j15dhkda.js";
|
|
78
|
+
import"../../index-673drwkn.js";
|
|
79
|
+
import"../../index-vmbxj75t.js";
|
|
38
80
|
import {
|
|
39
81
|
validateImageOptions,
|
|
40
82
|
inlineOrderedParts,
|
|
41
83
|
guardedTurnStarter
|
|
42
84
|
} from "../../index-y0a4gt1s.js";
|
|
43
|
-
import
|
|
85
|
+
import {
|
|
86
|
+
holdEngineRequest,
|
|
87
|
+
answerEngineRequest,
|
|
88
|
+
drainEngineRequests,
|
|
89
|
+
endEngineTurn,
|
|
90
|
+
loseEngineTurn
|
|
91
|
+
} from "../../index-gm9yz82v.js";
|
|
44
92
|
import {
|
|
45
93
|
spawnEngineProcess2
|
|
46
94
|
} from "../../index-rxh3qy4x.js";
|
|
@@ -48,11 +96,10 @@ import"../../index-3fym4j8n.js";
|
|
|
48
96
|
import {
|
|
49
97
|
planLimitsReadFailed2,
|
|
50
98
|
mergeRateLimitEvent2
|
|
51
|
-
} from "../../index-
|
|
99
|
+
} from "../../index-32vaajec.js";
|
|
100
|
+
import"../../index-pzhqydxb.js";
|
|
52
101
|
import {
|
|
53
|
-
|
|
54
|
-
assertExpectedOwnerUid,
|
|
55
|
-
unixSocketDirectoryViolation
|
|
102
|
+
assertExpectedOwnerUid
|
|
56
103
|
} from "../../index-hab790s6.js";
|
|
57
104
|
import {
|
|
58
105
|
errnoOf
|
|
@@ -71,29 +118,12 @@ import {
|
|
|
71
118
|
} from "../../index-agy5fqgf.js";
|
|
72
119
|
import {
|
|
73
120
|
abortReason,
|
|
74
|
-
raceAbort
|
|
121
|
+
raceAbort,
|
|
122
|
+
withLinkedAbortSignals
|
|
75
123
|
} from "../../index-rptj3qnc.js";
|
|
76
124
|
|
|
77
|
-
// src/agent-executor/codex/
|
|
125
|
+
// src/agent-executor/codex/notifications.ts
|
|
78
126
|
import { z } from "zod";
|
|
79
|
-
var CodexCollaborationModeSchema = z.strictObject({
|
|
80
|
-
mode: z.enum(["plan", "default"]),
|
|
81
|
-
settings: z.strictObject({
|
|
82
|
-
model: z.string().min(1),
|
|
83
|
-
reasoning_effort: z.string().min(1).nullable().optional(),
|
|
84
|
-
developer_instructions: z.string().nullable().optional()
|
|
85
|
-
})
|
|
86
|
-
});
|
|
87
|
-
var CodexThreadItemSchema = z.looseObject({
|
|
88
|
-
type: z.string(),
|
|
89
|
-
id: z.string().min(1)
|
|
90
|
-
});
|
|
91
|
-
var CodexTurnSchema = z.looseObject({
|
|
92
|
-
id: z.string().min(1),
|
|
93
|
-
status: z.enum(["completed", "interrupted", "failed", "inProgress"]),
|
|
94
|
-
error: z.looseObject({ message: z.string(), codexErrorInfo: z.json().nullable().optional() }).nullable().optional(),
|
|
95
|
-
items: z.array(z.looseObject({ type: z.string(), clientId: z.string().nullable().optional() })).optional()
|
|
96
|
-
});
|
|
97
127
|
var CodexTokenUsageBreakdownSchema = z.looseObject({
|
|
98
128
|
inputTokens: z.int().nonnegative().optional(),
|
|
99
129
|
outputTokens: z.int().nonnegative().optional(),
|
|
@@ -103,13 +133,67 @@ var CodexTokenUsageBreakdownSchema = z.looseObject({
|
|
|
103
133
|
totalTokens: z.int().nonnegative().optional()
|
|
104
134
|
});
|
|
105
135
|
var CodexNotificationParams = {
|
|
106
|
-
"item/agentMessage/delta": z.looseObject({
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
136
|
+
"item/agentMessage/delta": z.looseObject({
|
|
137
|
+
threadId: z.string().optional(),
|
|
138
|
+
turnId: z.string().optional(),
|
|
139
|
+
itemId: z.string(),
|
|
140
|
+
delta: z.string()
|
|
141
|
+
}),
|
|
142
|
+
"item/reasoning/textDelta": z.looseObject({
|
|
143
|
+
threadId: z.string().optional(),
|
|
144
|
+
turnId: z.string().optional(),
|
|
145
|
+
itemId: z.string(),
|
|
146
|
+
delta: z.string()
|
|
147
|
+
}),
|
|
148
|
+
"item/reasoning/summaryTextDelta": z.looseObject({
|
|
149
|
+
threadId: z.string().optional(),
|
|
150
|
+
turnId: z.string().optional(),
|
|
151
|
+
itemId: z.string(),
|
|
152
|
+
delta: z.string(),
|
|
153
|
+
summaryIndex: z.number().int().optional()
|
|
154
|
+
}),
|
|
155
|
+
"item/plan/delta": z.looseObject({
|
|
156
|
+
threadId: z.string().optional(),
|
|
157
|
+
turnId: z.string().optional(),
|
|
158
|
+
itemId: z.string(),
|
|
159
|
+
delta: z.string()
|
|
160
|
+
}),
|
|
161
|
+
"item/started": z.looseObject({
|
|
162
|
+
threadId: z.string().optional(),
|
|
163
|
+
turnId: z.string().optional(),
|
|
164
|
+
item: CodexThreadItemSchema2
|
|
165
|
+
}),
|
|
166
|
+
"item/completed": z.looseObject({
|
|
167
|
+
threadId: z.string().optional(),
|
|
168
|
+
turnId: z.string().optional(),
|
|
169
|
+
item: CodexThreadItemSchema2
|
|
170
|
+
}),
|
|
171
|
+
"turn/started": z.looseObject({
|
|
172
|
+
threadId: z.string().optional(),
|
|
173
|
+
turn: CodexTurnSchema
|
|
174
|
+
}),
|
|
175
|
+
"turn/completed": z.looseObject({
|
|
176
|
+
threadId: z.string().optional(),
|
|
177
|
+
turn: CodexTurnSchema
|
|
178
|
+
}),
|
|
179
|
+
"thread/status/changed": z.looseObject({
|
|
180
|
+
threadId: z.string(),
|
|
181
|
+
status: CodexThreadStatusSchema2
|
|
182
|
+
}),
|
|
183
|
+
"thread/settings/updated": z.looseObject({
|
|
184
|
+
threadId: z.string(),
|
|
185
|
+
threadSettings: z.looseObject({})
|
|
186
|
+
}),
|
|
187
|
+
"model/rerouted": z.looseObject({
|
|
188
|
+
threadId: z.string(),
|
|
189
|
+
turnId: z.string(),
|
|
190
|
+
fromModel: z.string(),
|
|
191
|
+
toModel: z.string(),
|
|
192
|
+
reason: z.string().optional()
|
|
193
|
+
}),
|
|
112
194
|
"thread/tokenUsage/updated": z.looseObject({
|
|
195
|
+
threadId: z.string().optional(),
|
|
196
|
+
turnId: z.string().optional(),
|
|
113
197
|
tokenUsage: z.looseObject({
|
|
114
198
|
last: z.looseObject({
|
|
115
199
|
inputTokens: z.int().nonnegative(),
|
|
@@ -123,144 +207,15 @@ var CodexNotificationParams = {
|
|
|
123
207
|
modelContextWindow: z.int().nonnegative().nullable().optional()
|
|
124
208
|
})
|
|
125
209
|
}),
|
|
126
|
-
"serverRequest/resolved": z.looseObject({
|
|
210
|
+
"serverRequest/resolved": z.looseObject({
|
|
211
|
+
threadId: z.string().optional(),
|
|
212
|
+
requestId: z.union([z.string(), z.int()])
|
|
213
|
+
}),
|
|
127
214
|
"account/rateLimits/updated": z.looseObject({
|
|
128
|
-
rateLimits:
|
|
129
|
-
rateLimitsByLimitId:
|
|
215
|
+
rateLimits: JsonRpcValueSchema2,
|
|
216
|
+
rateLimitsByLimitId: JsonRpcValueSchema2.optional()
|
|
130
217
|
})
|
|
131
218
|
};
|
|
132
|
-
var CodexApprovalParamsSchema = z.looseObject({
|
|
133
|
-
itemId: z.string(),
|
|
134
|
-
command: z.string().nullable().optional(),
|
|
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()
|
|
154
|
-
});
|
|
155
|
-
var CodexUserInputParamsSchema = z.looseObject({
|
|
156
|
-
itemId: z.string(),
|
|
157
|
-
questions: z.array(CodexUserInputQuestionSchema)
|
|
158
|
-
});
|
|
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
|
-
});
|
|
216
|
-
var CodexThreadContextSchema = z.object({
|
|
217
|
-
model: z.string().optional(),
|
|
218
|
-
modelProvider: z.string().optional(),
|
|
219
|
-
reasoningEffort: z.string().nullable().optional(),
|
|
220
|
-
approvalPolicy: z.json().optional(),
|
|
221
|
-
sandbox: z.json().optional(),
|
|
222
|
-
cwd: z.string().optional(),
|
|
223
|
-
runtimeWorkspaceRoots: z.array(z.string()).readonly().optional()
|
|
224
|
-
});
|
|
225
|
-
var CodexStartedThreadSchema = CodexThreadContextSchema.extend({
|
|
226
|
-
thread: z.looseObject({ id: z.string().min(1) })
|
|
227
|
-
}).loose();
|
|
228
|
-
function extractCodexThreadContext(parsed) {
|
|
229
|
-
return {
|
|
230
|
-
...parsed.model !== undefined && { model: parsed.model },
|
|
231
|
-
...parsed.modelProvider !== undefined && { modelProvider: parsed.modelProvider },
|
|
232
|
-
...parsed.reasoningEffort !== undefined && { reasoningEffort: parsed.reasoningEffort },
|
|
233
|
-
...parsed.approvalPolicy !== undefined && { approvalPolicy: parsed.approvalPolicy },
|
|
234
|
-
...parsed.sandbox !== undefined && { sandbox: parsed.sandbox },
|
|
235
|
-
...parsed.cwd !== undefined && { cwd: parsed.cwd },
|
|
236
|
-
...parsed.runtimeWorkspaceRoots !== undefined && {
|
|
237
|
-
runtimeWorkspaceRoots: parsed.runtimeWorkspaceRoots
|
|
238
|
-
}
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
var CodexStartedTurnSchema = z.looseObject({
|
|
242
|
-
turn: z.looseObject({ id: z.string().min(1) })
|
|
243
|
-
});
|
|
244
|
-
var CodexTurnSteerResponseSchema = z.looseObject({
|
|
245
|
-
turnId: z.string().min(1)
|
|
246
|
-
});
|
|
247
|
-
var CodexListedTurnItemSchema = z.looseObject({
|
|
248
|
-
type: z.string(),
|
|
249
|
-
clientId: z.string().nullable().optional()
|
|
250
|
-
});
|
|
251
|
-
var CodexListedTurnSchema = CodexTurnSchema.extend({
|
|
252
|
-
items: z.array(CodexListedTurnItemSchema),
|
|
253
|
-
itemsView: z.literal("full").optional()
|
|
254
|
-
});
|
|
255
|
-
var CodexTurnsPageSchema = z.looseObject({
|
|
256
|
-
data: z.array(CodexListedTurnSchema),
|
|
257
|
-
nextCursor: z.string().nullable().optional()
|
|
258
|
-
});
|
|
259
|
-
var CodexThreadRevertResponseSchema = z.looseObject({
|
|
260
|
-
thread: z.looseObject({ id: z.string().min(1) }),
|
|
261
|
-
turnsBackwardsCursor: z.string().nullable().optional(),
|
|
262
|
-
itemsBackwardsCursor: z.string().nullable().optional()
|
|
263
|
-
});
|
|
264
219
|
var CODEX_OPTED_OUT_NOTIFICATIONS = [
|
|
265
220
|
"app/list/updated",
|
|
266
221
|
"item/commandExecution/outputDelta",
|
|
@@ -320,375 +275,399 @@ var CODEX_QUIET_NOTIFICATIONS = new Set([
|
|
|
320
275
|
"modelProvider/authRecoveryCompleted",
|
|
321
276
|
"error"
|
|
322
277
|
]);
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
};
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
278
|
+
function parseCodexNotification(event) {
|
|
279
|
+
const { method, params } = event;
|
|
280
|
+
switch (method) {
|
|
281
|
+
case "item/agentMessage/delta":
|
|
282
|
+
return {
|
|
283
|
+
method,
|
|
284
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
285
|
+
};
|
|
286
|
+
case "item/reasoning/textDelta":
|
|
287
|
+
return {
|
|
288
|
+
method,
|
|
289
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
290
|
+
};
|
|
291
|
+
case "item/reasoning/summaryTextDelta":
|
|
292
|
+
return {
|
|
293
|
+
method,
|
|
294
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
295
|
+
};
|
|
296
|
+
case "item/plan/delta":
|
|
297
|
+
return {
|
|
298
|
+
method,
|
|
299
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
300
|
+
};
|
|
301
|
+
case "item/started":
|
|
302
|
+
return {
|
|
303
|
+
method,
|
|
304
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
305
|
+
};
|
|
306
|
+
case "item/completed":
|
|
307
|
+
return {
|
|
308
|
+
method,
|
|
309
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
310
|
+
};
|
|
311
|
+
case "turn/started":
|
|
312
|
+
return {
|
|
313
|
+
method,
|
|
314
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
315
|
+
};
|
|
316
|
+
case "turn/completed":
|
|
317
|
+
return {
|
|
318
|
+
method,
|
|
319
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
320
|
+
};
|
|
321
|
+
case "thread/status/changed":
|
|
322
|
+
return {
|
|
323
|
+
method,
|
|
324
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
325
|
+
};
|
|
326
|
+
case "thread/settings/updated":
|
|
327
|
+
return {
|
|
328
|
+
method,
|
|
329
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
330
|
+
};
|
|
331
|
+
case "model/rerouted":
|
|
332
|
+
return {
|
|
333
|
+
method,
|
|
334
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
335
|
+
};
|
|
336
|
+
case "thread/tokenUsage/updated":
|
|
337
|
+
return {
|
|
338
|
+
method,
|
|
339
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
340
|
+
};
|
|
341
|
+
case "serverRequest/resolved":
|
|
342
|
+
return {
|
|
343
|
+
method,
|
|
344
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
345
|
+
};
|
|
346
|
+
case "account/rateLimits/updated":
|
|
347
|
+
return {
|
|
348
|
+
method,
|
|
349
|
+
params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
|
|
350
|
+
};
|
|
351
|
+
default:
|
|
352
|
+
return null;
|
|
352
353
|
}
|
|
353
354
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
355
|
+
|
|
356
|
+
// src/agent-executor/codex/classify.ts
|
|
357
|
+
var raw = (type) => ({ source: "codex", type });
|
|
358
|
+
var CODEX_TOOL_ITEMS = new Set([
|
|
359
|
+
"commandExecution",
|
|
360
|
+
"fileChange",
|
|
361
|
+
"mcpToolCall",
|
|
362
|
+
"dynamicToolCall",
|
|
363
|
+
"collabAgentToolCall",
|
|
364
|
+
"webSearch",
|
|
365
|
+
"imageView",
|
|
366
|
+
"sleep",
|
|
367
|
+
"imageGeneration",
|
|
368
|
+
"functionCallOutput"
|
|
369
|
+
]);
|
|
370
|
+
var STATUSLESS_TOOL_ITEMS = new Set([
|
|
371
|
+
"webSearch",
|
|
372
|
+
"imageView",
|
|
373
|
+
"sleep",
|
|
374
|
+
"functionCallOutput"
|
|
375
|
+
]);
|
|
376
|
+
var CODEX_CONTENT_ITEMS = new Set([
|
|
377
|
+
"agentMessage",
|
|
378
|
+
"reasoning",
|
|
379
|
+
"userMessage",
|
|
380
|
+
"plan",
|
|
381
|
+
"contextCompaction",
|
|
382
|
+
"hookPrompt",
|
|
383
|
+
"subAgentActivity",
|
|
384
|
+
"enteredReviewMode",
|
|
385
|
+
"exitedReviewMode"
|
|
386
|
+
]);
|
|
387
|
+
var KNOWN_CODEX_ERROR_CODES = new Set([
|
|
388
|
+
"contextWindowExceeded",
|
|
389
|
+
"sessionBudgetExceeded",
|
|
390
|
+
"usageLimitExceeded",
|
|
391
|
+
"rateLimitExceeded",
|
|
392
|
+
"flexUnavailable",
|
|
393
|
+
"serverOverloaded",
|
|
394
|
+
"modelNotFound",
|
|
395
|
+
"policyCapacityUnavailable",
|
|
396
|
+
"cyberPolicy",
|
|
397
|
+
"bioPolicy",
|
|
398
|
+
"misalignmentPolicyViolation",
|
|
399
|
+
"tooManyDenials",
|
|
400
|
+
"internalServerError",
|
|
401
|
+
"unauthorized",
|
|
402
|
+
"badRequest",
|
|
403
|
+
"threadRollbackFailed",
|
|
404
|
+
"sandboxError",
|
|
405
|
+
"other",
|
|
406
|
+
"inferenceHookDenied"
|
|
407
|
+
]);
|
|
408
|
+
var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
|
|
409
|
+
"httpConnectionFailed",
|
|
410
|
+
"responseStreamConnectionFailed",
|
|
411
|
+
"responseStreamDisconnected",
|
|
412
|
+
"responseTooManyFailedAttempts",
|
|
413
|
+
"activeTurnNotSteerable"
|
|
414
|
+
]);
|
|
415
|
+
var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
|
|
416
|
+
function toolName(item) {
|
|
417
|
+
if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
|
|
418
|
+
return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
|
|
360
419
|
}
|
|
361
|
-
if (
|
|
362
|
-
|
|
420
|
+
if (item.type === "functionCallOutput") {
|
|
421
|
+
return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
|
|
363
422
|
}
|
|
364
|
-
|
|
423
|
+
return item.type;
|
|
365
424
|
}
|
|
366
|
-
function
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
} catch (error) {
|
|
370
|
-
if (errnoOf(error) === "ENOENT")
|
|
371
|
-
return;
|
|
372
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to inspect unix socket ${label} "${targetPath}"`, { cause: error });
|
|
373
|
-
}
|
|
425
|
+
function toolInput(item) {
|
|
426
|
+
const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
|
|
427
|
+
return safeJsonValue(rest);
|
|
374
428
|
}
|
|
375
|
-
function
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
throw new CodexUnixSocketError("target-refused", socketPath, violation);
|
|
429
|
+
function isKnownCodexErrorInfo(info) {
|
|
430
|
+
if (typeof info === "string")
|
|
431
|
+
return KNOWN_CODEX_ERROR_CODES.has(info);
|
|
432
|
+
if (typeof info === "object" && info !== null && !Array.isArray(info)) {
|
|
433
|
+
const keys = Object.keys(info);
|
|
434
|
+
return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
|
|
382
435
|
}
|
|
383
|
-
return
|
|
436
|
+
return false;
|
|
384
437
|
}
|
|
385
|
-
function
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
if (
|
|
389
|
-
|
|
438
|
+
function formatCodexErrorInfo(info) {
|
|
439
|
+
if (info === null || info === undefined)
|
|
440
|
+
return;
|
|
441
|
+
if (typeof info === "string") {
|
|
442
|
+
const trimmed = info.trim();
|
|
443
|
+
return trimmed.length > 0 ? trimmed.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS) : undefined;
|
|
390
444
|
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
445
|
+
try {
|
|
446
|
+
const serialized = JSON.stringify(safeJsonValue(info));
|
|
447
|
+
if (serialized === undefined || serialized.length === 0)
|
|
448
|
+
return;
|
|
449
|
+
return serialized.length > MAX_ERROR_INFO_SUMMARY_CHARS ? `${serialized.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS - 1)}…` : serialized;
|
|
450
|
+
} catch {
|
|
451
|
+
return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
|
|
394
452
|
}
|
|
395
453
|
}
|
|
396
|
-
function
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
if (stats === undefined)
|
|
404
|
-
return "absent";
|
|
405
|
-
if (requiredUid !== undefined && stats.uid !== requiredUid) {
|
|
406
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket "${socketPath}" is owned by uid ${stats.uid}, expected ${requiredUid}`);
|
|
407
|
-
}
|
|
408
|
-
if (stats.isSymbolicLink()) {
|
|
409
|
-
let resolved;
|
|
410
|
-
try {
|
|
411
|
-
resolved = realpathSync(socketPath);
|
|
412
|
-
} catch (error) {
|
|
413
|
-
if (errnoOf(error) === "ENOENT")
|
|
414
|
-
return "absent";
|
|
415
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to resolve unix socket symlink "${socketPath}"`, { cause: error });
|
|
416
|
-
}
|
|
417
|
-
if (assertPrivateDirStats(dirname(resolved), requiredUid, socketPath, caller) === "absent") {
|
|
418
|
-
return "absent";
|
|
419
|
-
}
|
|
420
|
-
const targetStats = lstatTarget(resolved, "resolved target", socketPath, caller);
|
|
421
|
-
if (targetStats === undefined)
|
|
422
|
-
return "absent";
|
|
423
|
-
if (!targetStats.isSocket()) {
|
|
424
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is not a socket`);
|
|
425
|
-
}
|
|
426
|
-
if (requiredUid !== undefined && targetStats.uid !== requiredUid) {
|
|
427
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is owned by uid ${targetStats.uid}, expected ${requiredUid}`);
|
|
454
|
+
function codexFailureMessage(turn) {
|
|
455
|
+
const rawMessage = turn.error?.message.trim() ?? "";
|
|
456
|
+
const info = turn.error?.codexErrorInfo;
|
|
457
|
+
const infoSummary = formatCodexErrorInfo(info);
|
|
458
|
+
if (rawMessage.length > 0) {
|
|
459
|
+
if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
|
|
460
|
+
return `${rawMessage} (${infoSummary})`;
|
|
428
461
|
}
|
|
429
|
-
return
|
|
462
|
+
return rawMessage;
|
|
430
463
|
}
|
|
431
|
-
if (
|
|
432
|
-
|
|
464
|
+
if (infoSummary !== undefined) {
|
|
465
|
+
return `Codex ended the turn ${turn.status} (${infoSummary})`;
|
|
433
466
|
}
|
|
434
|
-
return
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
// src/agent-executor/codex/ws-frame.ts
|
|
438
|
-
import { randomBytes } from "node:crypto";
|
|
439
|
-
var MAX_WS_FRAGMENTS = 1024;
|
|
440
|
-
var MAX_CONTROL_PAYLOAD_BYTES = 125;
|
|
441
|
-
function maskedWsFrameByteLength(payloadBytes) {
|
|
442
|
-
const headerLen = payloadBytes < 126 ? 2 : payloadBytes <= 65535 ? 4 : 10;
|
|
443
|
-
return headerLen + 4 + payloadBytes;
|
|
444
|
-
}
|
|
445
|
-
function encodeMaskedWsFrame(opcode, payload) {
|
|
446
|
-
const len = payload.byteLength;
|
|
447
|
-
const headerLen = len < 126 ? 2 : len <= 65535 ? 4 : 10;
|
|
448
|
-
const frame = Buffer.allocUnsafe(headerLen + 4 + len);
|
|
449
|
-
frame[0] = 128 | opcode & 15;
|
|
450
|
-
if (len < 126) {
|
|
451
|
-
frame[1] = 128 | len;
|
|
452
|
-
} else if (len <= 65535) {
|
|
453
|
-
frame[1] = 128 | 126;
|
|
454
|
-
frame.writeUInt16BE(len, 2);
|
|
455
|
-
} else {
|
|
456
|
-
frame[1] = 128 | 127;
|
|
457
|
-
const hi = Math.floor(len / 4294967296);
|
|
458
|
-
const lo = len >>> 0;
|
|
459
|
-
frame.writeUInt32BE(hi, 2);
|
|
460
|
-
frame.writeUInt32BE(lo, 6);
|
|
461
|
-
}
|
|
462
|
-
const mask = randomBytes(4);
|
|
463
|
-
frame[headerLen] = mask[0] ?? 0;
|
|
464
|
-
frame[headerLen + 1] = mask[1] ?? 0;
|
|
465
|
-
frame[headerLen + 2] = mask[2] ?? 0;
|
|
466
|
-
frame[headerLen + 3] = mask[3] ?? 0;
|
|
467
|
-
const bodyOffset = headerLen + 4;
|
|
468
|
-
for (let i = 0;i < len; i += 1) {
|
|
469
|
-
frame[bodyOffset + i] = (payload[i] ?? 0) ^ (mask[i & 3] ?? 0);
|
|
470
|
-
}
|
|
471
|
-
return frame;
|
|
472
|
-
}
|
|
473
|
-
function createByteQueue() {
|
|
474
|
-
const chunks = [];
|
|
475
|
-
let headOffset = 0;
|
|
476
|
-
let total = 0;
|
|
477
|
-
return {
|
|
478
|
-
get length() {
|
|
479
|
-
return total;
|
|
480
|
-
},
|
|
481
|
-
push(chunk) {
|
|
482
|
-
if (chunk.byteLength === 0)
|
|
483
|
-
return;
|
|
484
|
-
chunks.push(chunk);
|
|
485
|
-
total += chunk.byteLength;
|
|
486
|
-
},
|
|
487
|
-
peekBytes(count) {
|
|
488
|
-
const first = chunks[0];
|
|
489
|
-
if (first !== undefined && first.byteLength - headOffset >= count) {
|
|
490
|
-
return first.subarray(headOffset, headOffset + count);
|
|
491
|
-
}
|
|
492
|
-
const out = Buffer.allocUnsafe(count);
|
|
493
|
-
let written = 0;
|
|
494
|
-
let idx = 0;
|
|
495
|
-
let off = headOffset;
|
|
496
|
-
while (written < count && idx < chunks.length) {
|
|
497
|
-
const cur = chunks[idx];
|
|
498
|
-
if (cur === undefined)
|
|
499
|
-
break;
|
|
500
|
-
const take = Math.min(cur.byteLength - off, count - written);
|
|
501
|
-
cur.copy(out, written, off, off + take);
|
|
502
|
-
written += take;
|
|
503
|
-
idx += 1;
|
|
504
|
-
off = 0;
|
|
505
|
-
}
|
|
506
|
-
return out;
|
|
507
|
-
},
|
|
508
|
-
consume(count) {
|
|
509
|
-
const out = Buffer.allocUnsafe(count);
|
|
510
|
-
let written = 0;
|
|
511
|
-
while (written < count && chunks.length > 0) {
|
|
512
|
-
const cur = chunks[0];
|
|
513
|
-
if (cur === undefined)
|
|
514
|
-
break;
|
|
515
|
-
const avail = cur.byteLength - headOffset;
|
|
516
|
-
const take = Math.min(avail, count - written);
|
|
517
|
-
cur.copy(out, written, headOffset, headOffset + take);
|
|
518
|
-
written += take;
|
|
519
|
-
total -= take;
|
|
520
|
-
if (take === avail) {
|
|
521
|
-
chunks.shift();
|
|
522
|
-
headOffset = 0;
|
|
523
|
-
} else {
|
|
524
|
-
headOffset += take;
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
return out;
|
|
528
|
-
},
|
|
529
|
-
skip(count) {
|
|
530
|
-
let left = count;
|
|
531
|
-
while (left > 0 && chunks.length > 0) {
|
|
532
|
-
const cur = chunks[0];
|
|
533
|
-
if (cur === undefined)
|
|
534
|
-
break;
|
|
535
|
-
const avail = cur.byteLength - headOffset;
|
|
536
|
-
if (left >= avail) {
|
|
537
|
-
chunks.shift();
|
|
538
|
-
headOffset = 0;
|
|
539
|
-
total -= avail;
|
|
540
|
-
left -= avail;
|
|
541
|
-
} else {
|
|
542
|
-
headOffset += left;
|
|
543
|
-
total -= left;
|
|
544
|
-
left = 0;
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
},
|
|
548
|
-
clear() {
|
|
549
|
-
chunks.length = 0;
|
|
550
|
-
headOffset = 0;
|
|
551
|
-
total = 0;
|
|
552
|
-
}
|
|
553
|
-
};
|
|
467
|
+
return `Codex ended the turn ${turn.status}`;
|
|
554
468
|
}
|
|
555
|
-
function
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
const
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
469
|
+
function httpStatusOf(value, depth = 0) {
|
|
470
|
+
if (depth > 3 || typeof value !== "object" || value === null)
|
|
471
|
+
return;
|
|
472
|
+
const direct = Reflect.get(value, "httpStatusCode");
|
|
473
|
+
if (typeof direct === "number")
|
|
474
|
+
return direct;
|
|
475
|
+
for (const nested of Object.values(value)) {
|
|
476
|
+
const found = httpStatusOf(nested, depth + 1);
|
|
477
|
+
if (found !== undefined)
|
|
478
|
+
return found;
|
|
479
|
+
}
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
function failureKind(info) {
|
|
483
|
+
if (info === "unauthorized")
|
|
484
|
+
return "authRequired";
|
|
485
|
+
if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "sessionBudgetExceeded")
|
|
486
|
+
return "rateLimited";
|
|
487
|
+
const status = httpStatusOf(info);
|
|
488
|
+
if (status === 401 || status === 403)
|
|
489
|
+
return "authRequired";
|
|
490
|
+
if (status === 429)
|
|
491
|
+
return "rateLimited";
|
|
492
|
+
return "restartRecommended";
|
|
493
|
+
}
|
|
494
|
+
function normalizeCodexTokenTotals(rawTotals) {
|
|
495
|
+
if (rawTotals === undefined)
|
|
496
|
+
return;
|
|
497
|
+
const normalized = {
|
|
498
|
+
...rawTotals.inputTokens !== undefined && { inputTokens: rawTotals.inputTokens },
|
|
499
|
+
...rawTotals.outputTokens !== undefined && { outputTokens: rawTotals.outputTokens },
|
|
500
|
+
...rawTotals.cachedInputTokens !== undefined && {
|
|
501
|
+
cachedInputTokens: rawTotals.cachedInputTokens
|
|
502
|
+
},
|
|
503
|
+
...rawTotals.cacheWriteInputTokens !== undefined && {
|
|
504
|
+
cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
|
|
505
|
+
},
|
|
506
|
+
...rawTotals.reasoningOutputTokens !== undefined && {
|
|
507
|
+
thinkingTokens: rawTotals.reasoningOutputTokens
|
|
508
|
+
},
|
|
509
|
+
...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
|
|
510
|
+
};
|
|
511
|
+
return Object.keys(normalized).length > 0 ? normalized : undefined;
|
|
512
|
+
}
|
|
513
|
+
function classifyCodexTokenUsage(params, base) {
|
|
514
|
+
const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
|
|
515
|
+
const normalizedTotal = normalizeCodexTokenTotals(total);
|
|
516
|
+
return {
|
|
517
|
+
kind: "deltas",
|
|
518
|
+
deltas: [
|
|
519
|
+
{
|
|
520
|
+
type: "usage",
|
|
521
|
+
...base,
|
|
522
|
+
itemId: "usage",
|
|
523
|
+
raw: raw("thread/tokenUsage/updated"),
|
|
524
|
+
inputTokens: last.inputTokens,
|
|
525
|
+
outputTokens: last.outputTokens,
|
|
526
|
+
...last.cachedInputTokens !== undefined && {
|
|
527
|
+
cachedInputTokens: last.cachedInputTokens
|
|
528
|
+
},
|
|
529
|
+
...last.cacheWriteInputTokens !== undefined && {
|
|
530
|
+
cacheCreationInputTokens: last.cacheWriteInputTokens
|
|
531
|
+
},
|
|
532
|
+
...last.reasoningOutputTokens !== undefined && {
|
|
533
|
+
thinkingTokens: last.reasoningOutputTokens
|
|
534
|
+
},
|
|
535
|
+
...last.totalTokens !== undefined && { totalTokens: last.totalTokens },
|
|
536
|
+
...normalizedTotal !== undefined && { total: normalizedTotal }
|
|
537
|
+
}
|
|
538
|
+
]
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
function classifyCodexNotification(method, params, state) {
|
|
542
|
+
const base = { turnId: state.turnId };
|
|
543
|
+
switch (method) {
|
|
544
|
+
case "item/agentMessage/delta": {
|
|
545
|
+
const p = CodexNotificationParams[method].parse(params);
|
|
546
|
+
return {
|
|
547
|
+
kind: "deltas",
|
|
548
|
+
deltas: [{ type: "text", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }]
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
case "item/reasoning/textDelta":
|
|
552
|
+
case "item/reasoning/summaryTextDelta": {
|
|
553
|
+
const p = CodexNotificationParams[method].parse(params);
|
|
554
|
+
return {
|
|
555
|
+
kind: "deltas",
|
|
556
|
+
deltas: [
|
|
557
|
+
{ type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
|
|
558
|
+
]
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
case "item/started":
|
|
562
|
+
case "item/completed": {
|
|
563
|
+
const { item } = CodexNotificationParams[method].parse(params);
|
|
564
|
+
if (CODEX_CONTENT_ITEMS.has(item.type))
|
|
565
|
+
return { kind: "ignore", reason: `${method} ${item.type}` };
|
|
566
|
+
if (!CODEX_TOOL_ITEMS.has(item.type)) {
|
|
567
|
+
return {
|
|
568
|
+
kind: "unhandled",
|
|
569
|
+
delta: {
|
|
570
|
+
type: "error",
|
|
571
|
+
...base,
|
|
572
|
+
itemId: `unhandled:${item.id}`,
|
|
573
|
+
raw: raw(`${method}/${item.type}`),
|
|
574
|
+
kind: "unhandled",
|
|
575
|
+
message: `Codex item ${item.type} is not known to this driver`
|
|
650
576
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
if (method === "item/started") {
|
|
580
|
+
return {
|
|
581
|
+
kind: "deltas",
|
|
582
|
+
deltas: [
|
|
583
|
+
{
|
|
584
|
+
type: "tool-call",
|
|
585
|
+
...base,
|
|
586
|
+
itemId: `call:${item.id}`,
|
|
587
|
+
raw: raw(method),
|
|
588
|
+
callId: item.id,
|
|
589
|
+
toolName: toolName(item),
|
|
590
|
+
input: toolInput(item)
|
|
664
591
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
592
|
+
]
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
const status = Reflect.get(item, "status");
|
|
596
|
+
const failure = Reflect.get(item, "failure");
|
|
597
|
+
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");
|
|
598
|
+
const hasFailure = failure !== undefined && failure !== null;
|
|
599
|
+
const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
|
|
600
|
+
return {
|
|
601
|
+
kind: "deltas",
|
|
602
|
+
deltas: [
|
|
603
|
+
{
|
|
604
|
+
type: "tool-result",
|
|
605
|
+
...base,
|
|
606
|
+
itemId: `result:${item.id}`,
|
|
607
|
+
raw: raw(method),
|
|
608
|
+
callId: item.id,
|
|
609
|
+
toolName: toolName(item),
|
|
610
|
+
outcome,
|
|
611
|
+
...output !== undefined && output !== null && {
|
|
612
|
+
output: safeJsonValue(output)
|
|
682
613
|
}
|
|
683
|
-
handlers.onMessage(text);
|
|
684
614
|
}
|
|
685
|
-
|
|
615
|
+
]
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
case "turn/completed": {
|
|
619
|
+
const { turn } = CodexNotificationParams[method].parse(params);
|
|
620
|
+
const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
|
|
621
|
+
const deltas = [];
|
|
622
|
+
if (outcome === "failed") {
|
|
623
|
+
deltas.push({
|
|
624
|
+
type: "error",
|
|
625
|
+
...base,
|
|
626
|
+
itemId: "failure",
|
|
627
|
+
raw: raw(method),
|
|
628
|
+
kind: failureKind(turn.error?.codexErrorInfo),
|
|
629
|
+
message: codexFailureMessage(turn)
|
|
630
|
+
});
|
|
686
631
|
}
|
|
632
|
+
deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
|
|
633
|
+
return { kind: "end", deltas, outcome };
|
|
687
634
|
}
|
|
688
|
-
|
|
635
|
+
case "thread/tokenUsage/updated":
|
|
636
|
+
return classifyCodexTokenUsage(params, base);
|
|
637
|
+
case "serverRequest/resolved":
|
|
638
|
+
return {
|
|
639
|
+
kind: "resolved",
|
|
640
|
+
requestId: String(CodexNotificationParams[method].parse(params).requestId)
|
|
641
|
+
};
|
|
642
|
+
case "account/rateLimits/updated": {
|
|
643
|
+
const parsed = CodexNotificationParams[method].parse(params);
|
|
644
|
+
return {
|
|
645
|
+
kind: "limits",
|
|
646
|
+
rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
|
|
647
|
+
rateLimits: parsed.rateLimits,
|
|
648
|
+
rateLimitsByLimitId: parsed.rateLimitsByLimitId
|
|
649
|
+
} : parsed.rateLimits
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
default:
|
|
653
|
+
if (CODEX_QUIET_NOTIFICATIONS.has(method))
|
|
654
|
+
return { kind: "ignore", reason: method };
|
|
655
|
+
return {
|
|
656
|
+
kind: "unhandled",
|
|
657
|
+
delta: {
|
|
658
|
+
type: "error",
|
|
659
|
+
...base,
|
|
660
|
+
itemId: `unhandled:${method}`,
|
|
661
|
+
raw: raw(method),
|
|
662
|
+
kind: "unhandled",
|
|
663
|
+
message: `Codex notification ${method} is not known to this driver`
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
}
|
|
689
667
|
}
|
|
690
|
-
|
|
691
668
|
// src/agent-executor/codex/unix-socket.ts
|
|
669
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
670
|
+
import { createConnection } from "node:net";
|
|
692
671
|
var WS_MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
693
672
|
var MAX_HANDSHAKE_HEADER_BYTES = 64 * 1024;
|
|
694
673
|
var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15000;
|
|
@@ -700,7 +679,7 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
|
|
|
700
679
|
`);
|
|
701
680
|
const statusLine = lines[0] ?? "";
|
|
702
681
|
if (!/^HTTP\/1\.1 101(?:\s|$)/.test(statusLine)) {
|
|
703
|
-
throw new
|
|
682
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, `Codex Unix socket WebSocket upgrade failed: ${statusLine || "empty response"}`);
|
|
704
683
|
}
|
|
705
684
|
const headers = new Map;
|
|
706
685
|
for (let i = 1;i < lines.length; i += 1) {
|
|
@@ -709,7 +688,7 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
|
|
|
709
688
|
continue;
|
|
710
689
|
const colon = line.indexOf(":");
|
|
711
690
|
if (colon <= 0) {
|
|
712
|
-
throw new
|
|
691
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, "Codex Unix socket upgrade response contained a malformed HTTP header line");
|
|
713
692
|
}
|
|
714
693
|
const key = line.slice(0, colon).trim().toLowerCase();
|
|
715
694
|
const value = line.slice(colon + 1).trim();
|
|
@@ -717,30 +696,30 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
|
|
|
717
696
|
headers.set(key, existing === undefined ? value : `${existing}, ${value}`);
|
|
718
697
|
}
|
|
719
698
|
if ((headers.get("upgrade") ?? "").toLowerCase() !== "websocket") {
|
|
720
|
-
throw new
|
|
699
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Upgrade: websocket" header');
|
|
721
700
|
}
|
|
722
701
|
const connectionTokens = (headers.get("connection") ?? "").toLowerCase().split(",").map((token) => token.trim());
|
|
723
702
|
if (!connectionTokens.includes("upgrade")) {
|
|
724
|
-
throw new
|
|
703
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Connection: upgrade" header');
|
|
725
704
|
}
|
|
726
705
|
if (headers.get("sec-websocket-accept") !== expectedAccept) {
|
|
727
|
-
throw new
|
|
706
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, "Codex Unix socket upgrade response returned an invalid Sec-WebSocket-Accept header");
|
|
728
707
|
}
|
|
729
708
|
}
|
|
730
709
|
function classifyConnectError(error, socketPath) {
|
|
731
710
|
const code = errnoOf(error);
|
|
732
711
|
if (code === "ENOENT") {
|
|
733
|
-
return new
|
|
712
|
+
return new CodexUnixSocketError2("endpoint-absent", socketPath, `Codex Unix socket "${socketPath}" does not exist`, { cause: error });
|
|
734
713
|
}
|
|
735
714
|
if (code === "ECONNREFUSED") {
|
|
736
|
-
return new
|
|
715
|
+
return new CodexUnixSocketError2("endpoint-not-listening", socketPath, `Codex Unix socket "${socketPath}" refused connection`, { cause: error });
|
|
737
716
|
}
|
|
738
|
-
return new
|
|
717
|
+
return new CodexUnixSocketError2("connection-lost", socketPath, `Failed to connect to Codex Unix socket "${socketPath}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
739
718
|
}
|
|
740
719
|
function performWsUpgrade(input) {
|
|
741
|
-
const wsKey =
|
|
720
|
+
const wsKey = randomBytes(16).toString("base64");
|
|
742
721
|
const expectedAccept = createHash("sha1").update(`${wsKey}${WS_MAGIC_GUID}`).digest("base64");
|
|
743
|
-
return withSignalDeadline(input.handshakeTimeoutMs, input.signal, () => new
|
|
722
|
+
return withSignalDeadline(input.handshakeTimeoutMs, input.signal, () => new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket WebSocket handshake timed out after ${input.handshakeTimeoutMs} ms`), (handshakeSignal) => new Promise((resolve, reject) => {
|
|
744
723
|
let settled = false;
|
|
745
724
|
let handshakeBuf = Buffer.alloc(0);
|
|
746
725
|
const sock = createConnection({ path: input.socketPath });
|
|
@@ -773,7 +752,7 @@ Sec-WebSocket-Version: 13\r
|
|
|
773
752
|
const onData = (chunk) => {
|
|
774
753
|
const combinedLen = handshakeBuf.byteLength + chunk.byteLength;
|
|
775
754
|
if (handshakeBuf.byteLength > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
776
|
-
fail(new
|
|
755
|
+
fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
777
756
|
return;
|
|
778
757
|
}
|
|
779
758
|
const nextBuf = handshakeBuf.byteLength === 0 ? chunk : Buffer.concat([handshakeBuf, chunk]);
|
|
@@ -782,14 +761,14 @@ Sec-WebSocket-Version: 13\r
|
|
|
782
761
|
`);
|
|
783
762
|
if (boundary === -1) {
|
|
784
763
|
if (combinedLen > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
785
|
-
fail(new
|
|
764
|
+
fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
786
765
|
return;
|
|
787
766
|
}
|
|
788
767
|
handshakeBuf = nextBuf;
|
|
789
768
|
return;
|
|
790
769
|
}
|
|
791
770
|
if (boundary > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
792
|
-
fail(new
|
|
771
|
+
fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
793
772
|
return;
|
|
794
773
|
}
|
|
795
774
|
const headerText = nextBuf.subarray(0, boundary).toString("latin1");
|
|
@@ -806,7 +785,7 @@ Sec-WebSocket-Version: 13\r
|
|
|
806
785
|
resolve({ socket: sock, trailing: rest });
|
|
807
786
|
};
|
|
808
787
|
const onError = (error) => fail(classifyConnectError(error, input.socketPath));
|
|
809
|
-
const onClose = () => fail(new
|
|
788
|
+
const onClose = () => fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, "Codex Unix socket closed before completing WebSocket upgrade"));
|
|
810
789
|
handshakeSignal.addEventListener("abort", onAbort, { once: true });
|
|
811
790
|
sock.once("connect", onConnect);
|
|
812
791
|
sock.on("data", onData);
|
|
@@ -823,7 +802,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
823
802
|
input.connectSignal?.throwIfAborted();
|
|
824
803
|
const targetState = assertCodexUnixSocketClientTarget(input.socketPath, "connectCodexUnixSocket", input.expectedOwnerUid);
|
|
825
804
|
if (targetState === "absent") {
|
|
826
|
-
throw new
|
|
805
|
+
throw new CodexUnixSocketError2("endpoint-absent", input.socketPath, `Codex Unix socket "${input.socketPath}" does not exist`);
|
|
827
806
|
}
|
|
828
807
|
const maxFrameBytes = input.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
|
|
829
808
|
const maxPendingWriteBytes = input.maxPendingWriteBytes ?? DEFAULT_MAX_PENDING_WRITE_BYTES;
|
|
@@ -837,7 +816,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
837
816
|
throw abortReason(input.signal);
|
|
838
817
|
}
|
|
839
818
|
if (socket.destroyed) {
|
|
840
|
-
throw new
|
|
819
|
+
throw new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed during WebSocket upgrade`);
|
|
841
820
|
}
|
|
842
821
|
let closed = false;
|
|
843
822
|
let closeSent = false;
|
|
@@ -882,7 +861,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
882
861
|
}
|
|
883
862
|
};
|
|
884
863
|
const onSignalAbort = () => {
|
|
885
|
-
const err = new
|
|
864
|
+
const err = new CodexUnixSocketError2("connection-lost", input.socketPath, "Codex Unix socket connection aborted", { cause: abortReason(input.signal) });
|
|
886
865
|
socket.destroy();
|
|
887
866
|
finishClosed(err);
|
|
888
867
|
};
|
|
@@ -898,20 +877,20 @@ async function connectCodexUnixSocket(input) {
|
|
|
898
877
|
}
|
|
899
878
|
socket.end();
|
|
900
879
|
const suffix = reason.length > 0 ? `: ${reason}` : "";
|
|
901
|
-
finishClosed(new
|
|
880
|
+
finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket closed by peer (${code ?? "no-code"})${suffix}`));
|
|
902
881
|
},
|
|
903
882
|
onProtocolError: (message) => {
|
|
904
|
-
const err = new
|
|
883
|
+
const err = new CodexUnixSocketError2("connection-lost", input.socketPath, message);
|
|
905
884
|
socket.destroy();
|
|
906
885
|
finishClosed(err);
|
|
907
886
|
}
|
|
908
887
|
});
|
|
909
888
|
socket.on("data", (chunk) => decoder.push(chunk));
|
|
910
889
|
socket.on("error", (error) => {
|
|
911
|
-
finishClosed(new
|
|
890
|
+
finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket error: ${error.message}`, { cause: error }));
|
|
912
891
|
});
|
|
913
892
|
socket.on("close", () => {
|
|
914
|
-
finishClosed(new
|
|
893
|
+
finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed`));
|
|
915
894
|
});
|
|
916
895
|
if (trailing.byteLength > 0)
|
|
917
896
|
decoder.push(trailing);
|
|
@@ -920,7 +899,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
920
899
|
return {
|
|
921
900
|
send(text) {
|
|
922
901
|
if (closed || socket.destroyed || !socket.writable) {
|
|
923
|
-
throw new
|
|
902
|
+
throw new CodexUnixSocketError2("connection-lost", input.socketPath, "Codex Unix socket connection is closed");
|
|
924
903
|
}
|
|
925
904
|
const payloadBytes = Buffer.byteLength(text, "utf8");
|
|
926
905
|
const frameBytes = maskedWsFrameByteLength(payloadBytes);
|
|
@@ -973,14 +952,16 @@ function validateCodexTransportAndArgs(config) {
|
|
|
973
952
|
throw new TypeError(`[stitchkit] createCodexDriver: unsupported transport kind ${JSON.stringify(Reflect.get(Object(transport), "kind"))}`);
|
|
974
953
|
}
|
|
975
954
|
async function initializeCodexPeer(peer, version) {
|
|
976
|
-
await peer.request("initialize", {
|
|
955
|
+
const reply = await peer.request("initialize", {
|
|
977
956
|
clientInfo: { name: "stitchkit-agent-executor", version },
|
|
978
957
|
capabilities: {
|
|
979
958
|
experimentalApi: true,
|
|
980
959
|
optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
|
|
981
960
|
}
|
|
982
961
|
}, { timeoutMs: BOOTSTRAP_MS });
|
|
962
|
+
const parsed = parseCodexResponse("initialize", CodexInitializeResponseSchema, reply);
|
|
983
963
|
peer.notify("initialized");
|
|
964
|
+
return nonEmptyString(parsed.userAgent);
|
|
984
965
|
}
|
|
985
966
|
function sleepAbortable(ms, signal) {
|
|
986
967
|
if (signal.aborted)
|
|
@@ -1009,7 +990,7 @@ async function dialWithEngineRace(input) {
|
|
|
1009
990
|
exitedEarly = new Error(`Codex app-server failed before listening on "${input.socketPath}": ${error instanceof Error ? error.message : String(error)}${detail.length > 0 ? ` (${detail})` : ""}`, { cause: error });
|
|
1010
991
|
exitAbort.abort(exitedEarly);
|
|
1011
992
|
});
|
|
1012
|
-
return withSignalDeadline(input.listenTimeoutMs, input.signal, () => new
|
|
993
|
+
return withSignalDeadline(input.listenTimeoutMs, input.signal, () => new CodexUnixSocketError2("endpoint-absent", input.socketPath, `Codex app-server did not listen on "${input.socketPath}" within ${input.listenTimeoutMs} ms`), async (deadlineSignal) => {
|
|
1013
994
|
let delayMs = POLL_INITIAL_MS;
|
|
1014
995
|
for (;; ) {
|
|
1015
996
|
if (exitedEarly !== undefined)
|
|
@@ -1031,7 +1012,7 @@ async function dialWithEngineRace(input) {
|
|
|
1031
1012
|
} catch (error) {
|
|
1032
1013
|
if (exitedEarly !== undefined)
|
|
1033
1014
|
throw exitedEarly;
|
|
1034
|
-
const retryable = error instanceof
|
|
1015
|
+
const retryable = error instanceof CodexUnixSocketError2 && (error.kind === "endpoint-absent" || error.kind === "endpoint-not-listening");
|
|
1035
1016
|
if (!retryable)
|
|
1036
1017
|
throw error;
|
|
1037
1018
|
await raceAbort(sleepAbortable(delayMs, deadlineSignal), exitAbort.signal);
|
|
@@ -1040,77 +1021,14 @@ async function dialWithEngineRace(input) {
|
|
|
1040
1021
|
}
|
|
1041
1022
|
});
|
|
1042
1023
|
}
|
|
1043
|
-
async function
|
|
1044
|
-
|
|
1045
|
-
}, onStartupPhase) {
|
|
1046
|
-
const transport = config.transport ?? { kind: "stdio" };
|
|
1047
|
-
const extraArgs = config.serverArgs ?? [];
|
|
1048
|
-
if (transport.kind === "stdio") {
|
|
1049
|
-
const env = engineEnvironment2(profile, config.ambient);
|
|
1050
|
-
let endedError;
|
|
1051
|
-
let ready = false;
|
|
1052
|
-
const peer = createJsonRpcPeer2({
|
|
1053
|
-
header: "omitted",
|
|
1054
|
-
requestTimeoutMs: REQUEST_MS,
|
|
1055
|
-
send: (line) => engine.send(line),
|
|
1056
|
-
...handlers
|
|
1057
|
-
});
|
|
1058
|
-
const finishEnd = (error) => {
|
|
1059
|
-
if (endedError !== undefined)
|
|
1060
|
-
return;
|
|
1061
|
-
endedError = error;
|
|
1062
|
-
peer.close(error);
|
|
1063
|
-
if (ready)
|
|
1064
|
-
onEnd(error);
|
|
1065
|
-
};
|
|
1066
|
-
emitStartupPhase(onStartupPhase, "spawning");
|
|
1067
|
-
const engine = spawnEngineProcess2({
|
|
1068
|
-
executable: config.executable,
|
|
1069
|
-
args: [...config.prefix, "app-server", ...extraArgs],
|
|
1070
|
-
cwd,
|
|
1071
|
-
env,
|
|
1072
|
-
signal,
|
|
1073
|
-
...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
|
|
1074
|
-
});
|
|
1075
|
-
const reading = (async () => {
|
|
1076
|
-
try {
|
|
1077
|
-
for await (const line of engine.lines)
|
|
1078
|
-
peer.receive(line);
|
|
1079
|
-
finishEnd(new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`));
|
|
1080
|
-
} catch (error) {
|
|
1081
|
-
const failed = error instanceof Error ? error : new Error(String(error));
|
|
1082
|
-
finishEnd(failed);
|
|
1083
|
-
await engine.stop().catch(() => {
|
|
1084
|
-
return;
|
|
1085
|
-
});
|
|
1086
|
-
}
|
|
1087
|
-
})();
|
|
1088
|
-
try {
|
|
1089
|
-
emitStartupPhase(onStartupPhase, "initializing");
|
|
1090
|
-
await initializeCodexPeer(peer, config.version);
|
|
1091
|
-
const providerPid = await engine.pidReady ?? engine.pid;
|
|
1092
|
-
if (endedError !== undefined)
|
|
1093
|
-
throw endedError;
|
|
1094
|
-
ready = true;
|
|
1095
|
-
return { engine, peer, reading, providerPid };
|
|
1096
|
-
} catch (error) {
|
|
1097
|
-
await stopConnection({ engine, reading }, { error });
|
|
1098
|
-
throw error;
|
|
1099
|
-
}
|
|
1100
|
-
}
|
|
1101
|
-
let wsClient;
|
|
1102
|
-
let spawnedEngine;
|
|
1024
|
+
async function connectCodexStdio(config, profile, cwd, extraArgs, signal, handlers, onEnd, onStartupPhase) {
|
|
1025
|
+
const env = engineEnvironment2(profile, config.ambient);
|
|
1103
1026
|
let endedError;
|
|
1104
1027
|
let ready = false;
|
|
1105
1028
|
const peer = createJsonRpcPeer2({
|
|
1106
1029
|
header: "omitted",
|
|
1107
1030
|
requestTimeoutMs: REQUEST_MS,
|
|
1108
|
-
send: (line) =>
|
|
1109
|
-
if (wsClient === undefined) {
|
|
1110
|
-
throw new Error("Codex Unix socket transport is not connected");
|
|
1111
|
-
}
|
|
1112
|
-
wsClient.send(line);
|
|
1113
|
-
},
|
|
1031
|
+
send: (line) => engine.send(line),
|
|
1114
1032
|
...handlers
|
|
1115
1033
|
});
|
|
1116
1034
|
const finishEnd = (error) => {
|
|
@@ -1121,25 +1039,91 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1121
1039
|
if (ready)
|
|
1122
1040
|
onEnd(error);
|
|
1123
1041
|
};
|
|
1124
|
-
|
|
1042
|
+
emitStartupPhase(onStartupPhase, "spawning");
|
|
1043
|
+
const engine = spawnEngineProcess2({
|
|
1044
|
+
executable: config.executable,
|
|
1045
|
+
args: [...config.prefix, "app-server", ...extraArgs],
|
|
1046
|
+
cwd,
|
|
1047
|
+
env,
|
|
1048
|
+
signal,
|
|
1049
|
+
...config.maxFrameBytes !== undefined && { maxLineBytes: config.maxFrameBytes }
|
|
1050
|
+
});
|
|
1051
|
+
const reading = (async () => {
|
|
1125
1052
|
try {
|
|
1126
|
-
|
|
1053
|
+
for await (const line of engine.lines)
|
|
1054
|
+
peer.receive(line);
|
|
1055
|
+
finishEnd(new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`));
|
|
1127
1056
|
} catch (error) {
|
|
1128
1057
|
const failed = error instanceof Error ? error : new Error(String(error));
|
|
1129
1058
|
finishEnd(failed);
|
|
1130
|
-
|
|
1131
|
-
return;
|
|
1132
|
-
});
|
|
1133
|
-
spawnedEngine?.stop().catch(() => {
|
|
1059
|
+
await engine.stop().catch(() => {
|
|
1134
1060
|
return;
|
|
1135
1061
|
});
|
|
1136
1062
|
}
|
|
1137
|
-
};
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1063
|
+
})();
|
|
1064
|
+
try {
|
|
1065
|
+
emitStartupPhase(onStartupPhase, "initializing");
|
|
1066
|
+
const userAgent = await initializeCodexPeer(peer, config.version);
|
|
1067
|
+
const providerPid = await engine.pidReady ?? engine.pid;
|
|
1068
|
+
if (endedError !== undefined)
|
|
1069
|
+
throw endedError;
|
|
1070
|
+
ready = true;
|
|
1071
|
+
return { engine, peer, reading, providerPid, userAgent };
|
|
1072
|
+
} catch (error) {
|
|
1073
|
+
await stopConnection({ engine, reading }, { error });
|
|
1074
|
+
throw error;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd = () => {
|
|
1078
|
+
return;
|
|
1079
|
+
}, onStartupPhase) {
|
|
1080
|
+
const transport = config.transport ?? { kind: "stdio" };
|
|
1081
|
+
const extraArgs = config.serverArgs ?? [];
|
|
1082
|
+
if (transport.kind === "stdio") {
|
|
1083
|
+
return connectCodexStdio(config, profile, cwd, extraArgs, signal, handlers, onEnd, onStartupPhase);
|
|
1084
|
+
}
|
|
1085
|
+
let wsClient;
|
|
1086
|
+
let spawnedEngine;
|
|
1087
|
+
let endedError;
|
|
1088
|
+
let ready = false;
|
|
1089
|
+
const peer = createJsonRpcPeer2({
|
|
1090
|
+
header: "omitted",
|
|
1091
|
+
requestTimeoutMs: REQUEST_MS,
|
|
1092
|
+
send: (line) => {
|
|
1093
|
+
if (wsClient === undefined) {
|
|
1094
|
+
throw new Error("Codex Unix socket transport is not connected");
|
|
1095
|
+
}
|
|
1096
|
+
wsClient.send(line);
|
|
1097
|
+
},
|
|
1098
|
+
...handlers
|
|
1099
|
+
});
|
|
1100
|
+
const finishEnd = (error) => {
|
|
1101
|
+
if (endedError !== undefined)
|
|
1102
|
+
return;
|
|
1103
|
+
endedError = error;
|
|
1104
|
+
peer.close(error);
|
|
1105
|
+
if (ready)
|
|
1106
|
+
onEnd(error);
|
|
1107
|
+
};
|
|
1108
|
+
const onMessage = (line) => {
|
|
1109
|
+
try {
|
|
1110
|
+
peer.receive(line);
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
const failed = error instanceof Error ? error : new Error(String(error));
|
|
1113
|
+
finishEnd(failed);
|
|
1114
|
+
wsClient?.close().catch(() => {
|
|
1115
|
+
return;
|
|
1116
|
+
});
|
|
1117
|
+
spawnedEngine?.stop().catch(() => {
|
|
1118
|
+
return;
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
const onClose = (error) => {
|
|
1123
|
+
finishEnd(error);
|
|
1124
|
+
};
|
|
1125
|
+
if (transport.kind === "unix-listen") {
|
|
1126
|
+
assertCodexUnixListenTargetAvailable(transport.socketPath, "createCodexDriver");
|
|
1143
1127
|
const env = engineEnvironment2(profile, config.ambient);
|
|
1144
1128
|
emitStartupPhase(onStartupPhase, "spawning");
|
|
1145
1129
|
spawnedEngine = spawnEngineProcess2({
|
|
@@ -1155,13 +1139,13 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1155
1139
|
env,
|
|
1156
1140
|
signal,
|
|
1157
1141
|
stdoutMode: "drain",
|
|
1158
|
-
...config.
|
|
1142
|
+
...config.maxFrameBytes !== undefined && { maxLineBytes: config.maxFrameBytes }
|
|
1159
1143
|
});
|
|
1160
1144
|
try {
|
|
1161
1145
|
wsClient = await dialWithEngineRace({
|
|
1162
1146
|
socketPath: transport.socketPath,
|
|
1163
1147
|
listenTimeoutMs: transport.listenTimeoutMs ?? DEFAULT_LISTEN_TIMEOUT_MS,
|
|
1164
|
-
...config.
|
|
1148
|
+
...config.maxFrameBytes !== undefined && { maxFrameBytes: config.maxFrameBytes },
|
|
1165
1149
|
signal,
|
|
1166
1150
|
engine: spawnedEngine,
|
|
1167
1151
|
onMessage,
|
|
@@ -1182,7 +1166,7 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1182
1166
|
expectedOwnerUid: transport.expectedOwnerUid
|
|
1183
1167
|
},
|
|
1184
1168
|
signal,
|
|
1185
|
-
...config.
|
|
1169
|
+
...config.maxFrameBytes !== undefined && { maxFrameBytes: config.maxFrameBytes },
|
|
1186
1170
|
onMessage,
|
|
1187
1171
|
onClose
|
|
1188
1172
|
});
|
|
@@ -1207,141 +1191,213 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1207
1191
|
if (endedError !== undefined)
|
|
1208
1192
|
throw endedError;
|
|
1209
1193
|
emitStartupPhase(onStartupPhase, "initializing");
|
|
1210
|
-
await initializeCodexPeer(peer, config.version);
|
|
1194
|
+
const userAgent = await initializeCodexPeer(peer, config.version);
|
|
1211
1195
|
if (endedError !== undefined)
|
|
1212
1196
|
throw endedError;
|
|
1213
1197
|
const providerPid = spawnedEngine !== undefined ? await spawnedEngine.pidReady ?? spawnedEngine.pid : undefined;
|
|
1214
1198
|
if (endedError !== undefined)
|
|
1215
1199
|
throw endedError;
|
|
1216
1200
|
ready = true;
|
|
1217
|
-
return { engine: compositeEngine, peer, reading, providerPid };
|
|
1201
|
+
return { engine: compositeEngine, peer, reading, providerPid, userAgent };
|
|
1218
1202
|
} catch (error) {
|
|
1219
1203
|
await stopConnection({ engine: compositeEngine, reading }, { error });
|
|
1220
1204
|
throw error;
|
|
1221
1205
|
}
|
|
1222
1206
|
}
|
|
1223
1207
|
|
|
1224
|
-
// src/agent-executor/codex/
|
|
1208
|
+
// src/agent-executor/codex/responses.ts
|
|
1225
1209
|
import { z as z2 } from "zod";
|
|
1226
|
-
var
|
|
1227
|
-
var
|
|
1228
|
-
var
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1210
|
+
var KNOWN_ACCOUNT_TYPES = new Set(["apiKey", "chatgpt", "amazonBedrock", "gcp"]);
|
|
1211
|
+
var CodexEmptyResponseSchema = z2.looseObject({});
|
|
1212
|
+
var CodexReadThreadResponseSchema = z2.looseObject({
|
|
1213
|
+
thread: CodexThreadSchema2,
|
|
1214
|
+
readState: JsonRpcValueSchema2.nullable().optional()
|
|
1215
|
+
});
|
|
1216
|
+
var CodexResumeThreadResponseSchema = CodexStartedThreadSchema;
|
|
1217
|
+
var CodexThreadItemEntrySchema = z2.looseObject({
|
|
1218
|
+
turnId: z2.string(),
|
|
1219
|
+
item: CodexThreadItemSchema2,
|
|
1220
|
+
outputDeferred: z2.boolean().optional(),
|
|
1221
|
+
startedAtMs: z2.number().int().nullable().optional(),
|
|
1222
|
+
completedAtMs: z2.number().int().nullable().optional()
|
|
1223
|
+
});
|
|
1224
|
+
var CodexItemsPageSchema = z2.looseObject({
|
|
1225
|
+
data: z2.array(CodexThreadItemEntrySchema),
|
|
1226
|
+
nextCursor: z2.string().nullable().optional(),
|
|
1227
|
+
backwardsCursor: z2.string().nullable().optional()
|
|
1228
|
+
});
|
|
1229
|
+
var CodexThreadsPageSchema = z2.looseObject({
|
|
1230
|
+
data: z2.array(CodexThreadSchema2),
|
|
1231
|
+
nextCursor: z2.string().nullable().optional(),
|
|
1232
|
+
backwardsCursor: z2.string().nullable().optional(),
|
|
1233
|
+
readStates: z2.record(z2.string(), JsonRpcValueSchema2.nullable()).nullable().optional()
|
|
1232
1234
|
});
|
|
1233
|
-
var
|
|
1235
|
+
var CodexLoadedThreadsPageSchema = z2.looseObject({
|
|
1236
|
+
data: z2.array(z2.string()),
|
|
1237
|
+
nextCursor: z2.string().nullable().optional()
|
|
1238
|
+
});
|
|
1239
|
+
var CodexReasoningEffortOptionSchema = z2.looseObject({
|
|
1240
|
+
reasoningEffort: z2.string(),
|
|
1241
|
+
description: z2.string().optional()
|
|
1242
|
+
});
|
|
1243
|
+
var CodexModelSchema = z2.looseObject({
|
|
1244
|
+
id: z2.string().min(1),
|
|
1245
|
+
model: z2.string().optional(),
|
|
1246
|
+
displayName: z2.string().optional(),
|
|
1247
|
+
description: z2.string().optional(),
|
|
1248
|
+
hidden: z2.boolean().optional(),
|
|
1249
|
+
isDefault: z2.boolean().optional(),
|
|
1250
|
+
defaultReasoningEffort: z2.string().optional(),
|
|
1251
|
+
supportedReasoningEfforts: z2.array(CodexReasoningEffortOptionSchema).optional(),
|
|
1252
|
+
inputModalities: z2.array(z2.string()).optional(),
|
|
1253
|
+
upgrade: z2.string().nullable().optional(),
|
|
1254
|
+
defaultServiceTier: z2.string().nullable().optional(),
|
|
1255
|
+
modelSpecialty: z2.string().nullable().optional()
|
|
1256
|
+
});
|
|
1257
|
+
var CodexModelsPageSchema = z2.looseObject({
|
|
1258
|
+
data: z2.array(CodexModelSchema),
|
|
1259
|
+
nextCursor: z2.string().nullable().optional()
|
|
1260
|
+
});
|
|
1261
|
+
var CodexSkillMetadataSchema = z2.looseObject({
|
|
1262
|
+
name: z2.string(),
|
|
1263
|
+
description: z2.string().optional(),
|
|
1264
|
+
path: z2.string().optional(),
|
|
1265
|
+
scope: z2.string().optional(),
|
|
1266
|
+
enabled: z2.boolean().optional(),
|
|
1267
|
+
pluginId: z2.string().nullable().optional(),
|
|
1268
|
+
shortDescription: z2.string().nullable().optional(),
|
|
1269
|
+
interface: JsonRpcValueSchema2.nullable().optional(),
|
|
1270
|
+
dependencies: JsonRpcValueSchema2.nullable().optional()
|
|
1271
|
+
});
|
|
1272
|
+
var CodexSkillErrorInfoSchema = z2.looseObject({
|
|
1273
|
+
path: z2.string(),
|
|
1274
|
+
message: z2.string()
|
|
1275
|
+
});
|
|
1276
|
+
var CodexSkillsListEntrySchema = z2.looseObject({
|
|
1277
|
+
cwd: z2.string(),
|
|
1278
|
+
skills: z2.array(CodexSkillMetadataSchema),
|
|
1279
|
+
errors: z2.array(CodexSkillErrorInfoSchema).optional()
|
|
1280
|
+
});
|
|
1281
|
+
var CodexSkillsListResponseSchema = z2.looseObject({
|
|
1282
|
+
data: z2.array(CodexSkillsListEntrySchema)
|
|
1283
|
+
});
|
|
1284
|
+
var CodexCollaborationModePresetSchema = z2.looseObject({
|
|
1285
|
+
name: z2.string(),
|
|
1286
|
+
mode: z2.string().nullable().optional(),
|
|
1287
|
+
model: z2.string().nullable().optional(),
|
|
1288
|
+
reasoning_effort: z2.string().nullable().optional()
|
|
1289
|
+
});
|
|
1290
|
+
var CodexCollaborationModesResponseSchema = z2.looseObject({
|
|
1291
|
+
data: z2.array(CodexCollaborationModePresetSchema)
|
|
1292
|
+
});
|
|
1293
|
+
var CodexMcpServerStatusSchema = z2.looseObject({
|
|
1294
|
+
name: z2.string(),
|
|
1295
|
+
authStatus: z2.string().optional(),
|
|
1296
|
+
runtimeStatus: z2.union([z2.string(), z2.looseObject({ type: z2.string() })]).nullable().optional(),
|
|
1297
|
+
tools: z2.record(z2.string(), JsonRpcValueSchema2).optional(),
|
|
1298
|
+
resources: z2.array(JsonRpcValueSchema2).optional(),
|
|
1299
|
+
resourceTemplates: z2.array(JsonRpcValueSchema2).optional(),
|
|
1300
|
+
environmentId: z2.string().nullable().optional(),
|
|
1301
|
+
httpOrigin: z2.string().nullable().optional(),
|
|
1302
|
+
pluginId: z2.string().nullable().optional(),
|
|
1303
|
+
serverInfo: JsonRpcValueSchema2.nullable().optional(),
|
|
1304
|
+
serverCapabilities: JsonRpcValueSchema2.optional(),
|
|
1305
|
+
toolListMeta: JsonRpcValueSchema2.optional(),
|
|
1306
|
+
toolsError: z2.string().nullable().optional()
|
|
1307
|
+
});
|
|
1308
|
+
var CodexMcpServerStatusPageSchema = z2.looseObject({
|
|
1309
|
+
data: z2.array(CodexMcpServerStatusSchema),
|
|
1310
|
+
nextCursor: z2.string().nullable().optional()
|
|
1311
|
+
});
|
|
1312
|
+
var CodexConfigSchema = z2.looseObject({
|
|
1313
|
+
model: z2.string().nullable().optional(),
|
|
1314
|
+
model_provider: z2.string().nullable().optional(),
|
|
1315
|
+
model_reasoning_effort: z2.string().nullable().optional(),
|
|
1316
|
+
model_reasoning_summary: z2.string().nullable().optional(),
|
|
1317
|
+
model_verbosity: z2.string().nullable().optional(),
|
|
1318
|
+
model_context_window: z2.number().int().nullable().optional(),
|
|
1319
|
+
approval_policy: CodexApprovalPolicySchema2.nullable().optional(),
|
|
1320
|
+
approvals_reviewer: z2.string().nullable().optional(),
|
|
1321
|
+
sandbox_mode: z2.string().nullable().optional(),
|
|
1322
|
+
service_tier: z2.string().nullable().optional(),
|
|
1323
|
+
review_model: z2.string().nullable().optional(),
|
|
1324
|
+
instructions: z2.string().nullable().optional(),
|
|
1325
|
+
developer_instructions: z2.string().nullable().optional(),
|
|
1326
|
+
compact_prompt: z2.string().nullable().optional()
|
|
1327
|
+
});
|
|
1328
|
+
var CodexConfigLayerMetadataSchema = z2.looseObject({
|
|
1329
|
+
name: JsonRpcValueSchema2,
|
|
1330
|
+
version: z2.string()
|
|
1331
|
+
});
|
|
1332
|
+
var CodexConfigReadResponseSchema = z2.looseObject({
|
|
1333
|
+
config: CodexConfigSchema,
|
|
1334
|
+
origins: z2.record(z2.string(), CodexConfigLayerMetadataSchema).optional(),
|
|
1335
|
+
layers: z2.array(JsonRpcValueSchema2).nullable().optional()
|
|
1336
|
+
});
|
|
1337
|
+
var CodexAccountSchema = z2.union([
|
|
1338
|
+
z2.looseObject({ type: z2.literal("apiKey") }),
|
|
1339
|
+
z2.looseObject({
|
|
1340
|
+
type: z2.literal("chatgpt"),
|
|
1341
|
+
email: z2.string().nullable().optional(),
|
|
1342
|
+
planType: z2.string().nullable().optional(),
|
|
1343
|
+
workspaceName: z2.string().nullable().optional()
|
|
1344
|
+
}),
|
|
1345
|
+
z2.looseObject({
|
|
1346
|
+
type: z2.literal("amazonBedrock"),
|
|
1347
|
+
usesCodexManagedCredentials: z2.boolean().optional()
|
|
1348
|
+
}),
|
|
1349
|
+
z2.looseObject({ type: z2.literal("gcp") }),
|
|
1350
|
+
unknownTypedRecordSchema(KNOWN_ACCOUNT_TYPES)
|
|
1351
|
+
]);
|
|
1352
|
+
var CodexAccountReadResponseSchema = z2.looseObject({
|
|
1353
|
+
account: CodexAccountSchema.nullable().optional(),
|
|
1354
|
+
requiresOpenaiAuth: z2.boolean(),
|
|
1355
|
+
userId: z2.string().nullable().optional(),
|
|
1356
|
+
workspaceRouting: JsonRpcValueSchema2.nullable().optional()
|
|
1357
|
+
});
|
|
1358
|
+
var CodexRateLimitWindowSchema = z2.looseObject({
|
|
1359
|
+
usedPercent: z2.number(),
|
|
1360
|
+
windowDurationMins: z2.number().int().nullable().optional(),
|
|
1361
|
+
resetsAt: z2.number().int().nullable().optional()
|
|
1362
|
+
});
|
|
1363
|
+
var CodexRateLimitSnapshotSchema = z2.looseObject({
|
|
1234
1364
|
limitId: z2.string().nullable().optional(),
|
|
1235
1365
|
limitName: z2.string().nullable().optional(),
|
|
1236
|
-
|
|
1237
|
-
|
|
1366
|
+
normalModelSlug: z2.string().nullable().optional(),
|
|
1367
|
+
planType: z2.string().nullable().optional(),
|
|
1368
|
+
primary: CodexRateLimitWindowSchema.nullable().optional(),
|
|
1369
|
+
secondary: CodexRateLimitWindowSchema.nullable().optional(),
|
|
1370
|
+
credits: JsonRpcValueSchema2.nullable().optional(),
|
|
1371
|
+
individualLimit: JsonRpcValueSchema2.nullable().optional(),
|
|
1372
|
+
rateLimitReachedType: z2.string().nullable().optional(),
|
|
1373
|
+
spendControlReached: z2.boolean().nullable().optional()
|
|
1374
|
+
});
|
|
1375
|
+
var CodexRateLimitsResponseSchema = z2.looseObject({
|
|
1376
|
+
rateLimits: CodexRateLimitSnapshotSchema,
|
|
1377
|
+
rateLimitsByLimitId: z2.record(z2.string(), CodexRateLimitSnapshotSchema).nullable().optional(),
|
|
1378
|
+
accountId: z2.string().nullable().optional(),
|
|
1379
|
+
ordinaryUsageAllowed: z2.boolean().nullable().optional(),
|
|
1380
|
+
rateLimitResetCredits: JsonRpcValueSchema2.nullable().optional(),
|
|
1381
|
+
rateLimitUpsell: JsonRpcValueSchema2.optional()
|
|
1382
|
+
});
|
|
1383
|
+
var CodexThreadUnsubscribeStatusSchema = z2.union([
|
|
1384
|
+
z2.enum(["notLoaded", "notSubscribed", "unsubscribed"]),
|
|
1385
|
+
z2.custom((value) => typeof value === "string" && value.length > 0, {
|
|
1386
|
+
message: "Expected a non-empty ThreadUnsubscribeStatus string"
|
|
1387
|
+
})
|
|
1388
|
+
]);
|
|
1389
|
+
var CodexThreadUnsubscribeResponseSchema = z2.looseObject({
|
|
1390
|
+
status: CodexThreadUnsubscribeStatusSchema
|
|
1391
|
+
});
|
|
1392
|
+
var CodexThreadUnarchiveResponseSchema = z2.looseObject({
|
|
1393
|
+
thread: CodexThreadSchema2
|
|
1394
|
+
});
|
|
1395
|
+
var CodexThreadMetadataUpdateResponseSchema = z2.looseObject({
|
|
1396
|
+
thread: CodexThreadSchema2
|
|
1238
1397
|
});
|
|
1239
|
-
function positiveSafeInt(value) {
|
|
1240
|
-
return isPositiveSafeInteger(value) ? value : undefined;
|
|
1241
|
-
}
|
|
1242
|
-
function clampLabel(value) {
|
|
1243
|
-
const trimmed = nonEmptyString(value)?.trim();
|
|
1244
|
-
if (trimmed === undefined)
|
|
1245
|
-
return;
|
|
1246
|
-
return trimmed.slice(0, MAX_WINDOW_NAME_CHARS);
|
|
1247
|
-
}
|
|
1248
|
-
function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
|
|
1249
|
-
const label = clampLabel(snapshot.limitName);
|
|
1250
|
-
const primary = snapshot.primary ?? undefined;
|
|
1251
|
-
const secondary = snapshot.secondary ?? undefined;
|
|
1252
|
-
const primaryMins = positiveSafeInt(primary?.windowDurationMins);
|
|
1253
|
-
const secondaryMins = positiveSafeInt(secondary?.windowDurationMins);
|
|
1254
|
-
const duplicateDuration = primary !== undefined && secondary !== undefined && primaryMins !== undefined && primaryMins === secondaryMins;
|
|
1255
|
-
const slots = [
|
|
1256
|
-
["primary", primary, primaryMins],
|
|
1257
|
-
["secondary", secondary, secondaryMins]
|
|
1258
|
-
];
|
|
1259
|
-
for (const [slot, window, mins] of slots) {
|
|
1260
|
-
if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
|
|
1261
|
-
continue;
|
|
1262
|
-
const suffix = mins === undefined ? `:${slot}` : duplicateDuration ? `:${mins}m:${slot}` : `:${mins}m`;
|
|
1263
|
-
const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
|
|
1264
|
-
const resetsAt = window.resetsAt !== undefined && window.resetsAt !== null && window.resetsAt > 0 ? epochSecondsToIso(window.resetsAt) : undefined;
|
|
1265
|
-
out.push(PlanWindowSchema2.parse({
|
|
1266
|
-
name,
|
|
1267
|
-
usedPercent: Math.min(100, window.usedPercent),
|
|
1268
|
-
...resetsAt !== undefined && { resetsAt },
|
|
1269
|
-
...mins !== undefined && { windowDurationMins: mins },
|
|
1270
|
-
...label !== undefined && { label }
|
|
1271
|
-
}));
|
|
1272
|
-
}
|
|
1273
|
-
}
|
|
1274
|
-
function isPlainRecord(value) {
|
|
1275
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1276
|
-
}
|
|
1277
|
-
function codexPlanWindows(reported) {
|
|
1278
|
-
const windows = [];
|
|
1279
|
-
const seenNames = new Set;
|
|
1280
|
-
if (isPlainRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported))) {
|
|
1281
|
-
const seenLimitIds = new Set;
|
|
1282
|
-
const rawById = reported.rateLimitsByLimitId;
|
|
1283
|
-
if (isPlainRecord(rawById)) {
|
|
1284
|
-
for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
|
|
1285
|
-
const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
|
|
1286
|
-
if (!parsed.success)
|
|
1287
|
-
continue;
|
|
1288
|
-
const limitId = nonEmptyString(parsed.data.limitId)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
|
|
1289
|
-
seenLimitIds.add(limitId);
|
|
1290
|
-
appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
|
|
1291
|
-
if (windows.length >= MAX_PLAN_WINDOWS)
|
|
1292
|
-
return windows;
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
if (windows.length < MAX_PLAN_WINDOWS && reported.rateLimits !== undefined) {
|
|
1296
|
-
const parsedSingle = SnapshotSchema.safeParse(reported.rateLimits);
|
|
1297
|
-
if (parsedSingle.success) {
|
|
1298
|
-
const explicitId = nonEmptyString(parsedSingle.data.limitId)?.trim();
|
|
1299
|
-
const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
|
|
1300
|
-
if (shouldIncludeSingle) {
|
|
1301
|
-
appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
|
|
1302
|
-
}
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
return windows;
|
|
1306
|
-
}
|
|
1307
|
-
const single = SnapshotSchema.safeParse(reported);
|
|
1308
|
-
if (!single.success)
|
|
1309
|
-
return [];
|
|
1310
|
-
const limitId = nonEmptyString(single.data.limitId)?.trim() ?? "limit";
|
|
1311
|
-
appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
|
|
1312
|
-
return windows;
|
|
1313
|
-
}
|
|
1314
1398
|
|
|
1315
|
-
// src/agent-executor/codex/thread-
|
|
1316
|
-
var MAX_UINT32 = 4294967295;
|
|
1399
|
+
// src/agent-executor/codex/thread-list-query.ts
|
|
1317
1400
|
var MAX_THREAD_LIST_IDS = 100;
|
|
1318
|
-
function assertNonEmptyThreadId(threadId, caller) {
|
|
1319
|
-
if (typeof threadId !== "string" || threadId.trim().length === 0) {
|
|
1320
|
-
throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
|
|
1321
|
-
}
|
|
1322
|
-
return threadId;
|
|
1323
|
-
}
|
|
1324
|
-
function assertRequiredNonEmptyString(value, field, caller) {
|
|
1325
|
-
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1326
|
-
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1327
|
-
}
|
|
1328
|
-
return value;
|
|
1329
|
-
}
|
|
1330
|
-
function assertOptionalNonEmptyString(value, field, caller) {
|
|
1331
|
-
if (value === undefined)
|
|
1332
|
-
return;
|
|
1333
|
-
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1334
|
-
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1335
|
-
}
|
|
1336
|
-
}
|
|
1337
|
-
function assertOptionalLimit(limit, caller) {
|
|
1338
|
-
if (limit === undefined || limit === null)
|
|
1339
|
-
return;
|
|
1340
|
-
assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
|
|
1341
|
-
if (limit > MAX_UINT32) {
|
|
1342
|
-
throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
1401
|
function assertBoundedThreadIdFilter(ids, field, caller) {
|
|
1346
1402
|
if (ids === undefined || ids === null)
|
|
1347
1403
|
return ids;
|
|
@@ -1423,120 +1479,186 @@ function buildListThreadsPayload(params) {
|
|
|
1423
1479
|
...params?.useStateDbOnly !== undefined && { useStateDbOnly: params.useStateDbOnly }
|
|
1424
1480
|
};
|
|
1425
1481
|
}
|
|
1426
|
-
|
|
1482
|
+
|
|
1483
|
+
// src/agent-executor/codex/thread-controls.ts
|
|
1484
|
+
var MAX_UINT32 = 4294967295;
|
|
1485
|
+
function validateCodexRpcCallOptions(options) {
|
|
1486
|
+
if (options === undefined)
|
|
1487
|
+
return;
|
|
1488
|
+
if (options.timeoutMs !== undefined) {
|
|
1489
|
+
assertTimerMs("timeoutMs", options.timeoutMs);
|
|
1490
|
+
}
|
|
1491
|
+
if (options.signal?.aborted) {
|
|
1492
|
+
throw abortReason(options.signal);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
function assertNonEmptyThreadId(threadId, caller) {
|
|
1496
|
+
if (typeof threadId !== "string" || threadId.trim().length === 0) {
|
|
1497
|
+
throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
|
|
1498
|
+
}
|
|
1499
|
+
return threadId;
|
|
1500
|
+
}
|
|
1501
|
+
function assertRequiredNonEmptyString(value, field, caller) {
|
|
1502
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1503
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1504
|
+
}
|
|
1505
|
+
return value;
|
|
1506
|
+
}
|
|
1507
|
+
function assertOptionalNonEmptyString(value, field, caller) {
|
|
1508
|
+
if (value === undefined)
|
|
1509
|
+
return;
|
|
1510
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1511
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
function assertOptionalNonEmptyNoNulString(value, field, caller) {
|
|
1515
|
+
if (value === undefined)
|
|
1516
|
+
return;
|
|
1517
|
+
if (typeof value !== "string" || value.trim().length === 0 || value.includes("\x00")) {
|
|
1518
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string without NUL bytes`);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
function assertOptionalLimit(limit, caller) {
|
|
1522
|
+
if (limit === undefined || limit === null)
|
|
1523
|
+
return;
|
|
1524
|
+
assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
|
|
1525
|
+
if (limit > MAX_UINT32) {
|
|
1526
|
+
throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
function createCodexThreadControlMethods(call, options = {}) {
|
|
1427
1530
|
return {
|
|
1428
|
-
async revertThread(params) {
|
|
1531
|
+
async revertThread(params, rpcOptions) {
|
|
1429
1532
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.revertThread");
|
|
1430
1533
|
const beforeTurnId = assertRequiredNonEmptyString(params.beforeTurnId, "beforeTurnId", "CodexControlClient.revertThread");
|
|
1431
|
-
const rawReply = await call("thread/revert", { threadId, beforeTurnId });
|
|
1432
|
-
const parsed = CodexThreadRevertResponseSchema
|
|
1534
|
+
const rawReply = await call("thread/revert", { threadId, beforeTurnId }, rpcOptions);
|
|
1535
|
+
const parsed = parseCodexResponse("thread/revert", CodexThreadRevertResponseSchema, rawReply);
|
|
1433
1536
|
return {
|
|
1434
|
-
thread:
|
|
1537
|
+
thread: parsed.thread,
|
|
1435
1538
|
turnsBackwardsCursor: parsed.turnsBackwardsCursor ?? null,
|
|
1436
1539
|
itemsBackwardsCursor: parsed.itemsBackwardsCursor ?? null
|
|
1437
1540
|
};
|
|
1438
1541
|
},
|
|
1439
|
-
async injectItems(params) {
|
|
1542
|
+
async injectItems(params, rpcOptions) {
|
|
1440
1543
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.injectItems");
|
|
1441
1544
|
if (!Array.isArray(params.items)) {
|
|
1442
1545
|
throw new TypeError("[stitchkit] CodexControlClient.injectItems: items must be an array");
|
|
1443
1546
|
}
|
|
1444
1547
|
const items = params.items.map((item) => safeJsonValue(item));
|
|
1445
|
-
|
|
1548
|
+
const raw = await call("thread/inject_items", { threadId, items }, rpcOptions);
|
|
1549
|
+
parseCodexResponse("thread/inject_items", CodexEmptyResponseSchema, raw);
|
|
1446
1550
|
},
|
|
1447
|
-
async unsubscribeThread(params) {
|
|
1551
|
+
async unsubscribeThread(params, rpcOptions) {
|
|
1448
1552
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unsubscribeThread");
|
|
1449
|
-
return call("thread/unsubscribe", { threadId });
|
|
1553
|
+
return parseCodexResponse("thread/unsubscribe", CodexThreadUnsubscribeResponseSchema, await call("thread/unsubscribe", { threadId }, rpcOptions));
|
|
1450
1554
|
},
|
|
1451
|
-
async listThreads(params) {
|
|
1452
|
-
return call("thread/list", buildListThreadsPayload(params));
|
|
1555
|
+
async listThreads(params, rpcOptions) {
|
|
1556
|
+
return parseCodexResponse("thread/list", CodexThreadsPageSchema, await call("thread/list", buildListThreadsPayload(params), rpcOptions));
|
|
1453
1557
|
},
|
|
1454
|
-
async listLoadedThreads(params) {
|
|
1558
|
+
async listLoadedThreads(params, rpcOptions) {
|
|
1455
1559
|
assertOptionalLimit(params?.limit, "CodexControlClient.listLoadedThreads");
|
|
1456
|
-
return call("thread/loaded/list", {
|
|
1560
|
+
return parseCodexResponse("thread/loaded/list", CodexLoadedThreadsPageSchema, await call("thread/loaded/list", {
|
|
1457
1561
|
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1458
1562
|
...params?.limit !== undefined && { limit: params.limit }
|
|
1459
|
-
});
|
|
1563
|
+
}, rpcOptions));
|
|
1460
1564
|
},
|
|
1461
|
-
async archiveThread(params) {
|
|
1565
|
+
async archiveThread(params, rpcOptions) {
|
|
1462
1566
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.archiveThread");
|
|
1463
|
-
|
|
1567
|
+
const raw = await call("thread/archive", { threadId }, rpcOptions);
|
|
1568
|
+
parseCodexResponse("thread/archive", CodexEmptyResponseSchema, raw);
|
|
1464
1569
|
},
|
|
1465
|
-
async unarchiveThread(params) {
|
|
1570
|
+
async unarchiveThread(params, rpcOptions) {
|
|
1466
1571
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unarchiveThread");
|
|
1467
|
-
return call("thread/unarchive", { threadId });
|
|
1572
|
+
return parseCodexResponse("thread/unarchive", CodexThreadUnarchiveResponseSchema, await call("thread/unarchive", { threadId }, rpcOptions));
|
|
1468
1573
|
},
|
|
1469
|
-
async updateThreadMetadata(params) {
|
|
1574
|
+
async updateThreadMetadata(params, rpcOptions) {
|
|
1470
1575
|
const caller = "CodexControlClient.updateThreadMetadata";
|
|
1471
1576
|
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1472
1577
|
const gitInfo = validateGitInfoUpdate(params.gitInfo, caller);
|
|
1473
|
-
return call("thread/metadata/update", {
|
|
1578
|
+
return parseCodexResponse("thread/metadata/update", CodexThreadMetadataUpdateResponseSchema, await call("thread/metadata/update", {
|
|
1474
1579
|
threadId,
|
|
1475
1580
|
...gitInfo !== undefined && { gitInfo }
|
|
1476
|
-
});
|
|
1581
|
+
}, rpcOptions));
|
|
1477
1582
|
},
|
|
1478
|
-
async setThreadName(params) {
|
|
1583
|
+
async setThreadName(params, rpcOptions) {
|
|
1479
1584
|
const caller = "CodexControlClient.setThreadName";
|
|
1480
1585
|
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1481
1586
|
const name = assertRequiredNonEmptyString(params.name, "name", caller);
|
|
1482
|
-
|
|
1587
|
+
const raw = await call("thread/name/set", { threadId, name }, rpcOptions);
|
|
1588
|
+
parseCodexResponse("thread/name/set", CodexEmptyResponseSchema, raw);
|
|
1589
|
+
},
|
|
1590
|
+
async interruptTurn(params, rpcOptions) {
|
|
1591
|
+
options.ensureAlive?.();
|
|
1592
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1593
|
+
const caller = "CodexControlClient.interruptTurn";
|
|
1594
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1595
|
+
const turnId = assertRequiredNonEmptyString(params.turnId, "turnId", caller);
|
|
1596
|
+
options.onBeforeInterruptTurn?.(threadId, turnId);
|
|
1597
|
+
await call("turn/interrupt", { threadId, turnId }, rpcOptions);
|
|
1598
|
+
},
|
|
1599
|
+
async compactThread(params, rpcOptions) {
|
|
1600
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.compactThread");
|
|
1601
|
+
await call("thread/compact/start", { threadId }, rpcOptions);
|
|
1483
1602
|
}
|
|
1484
1603
|
};
|
|
1485
1604
|
}
|
|
1486
1605
|
|
|
1487
|
-
// src/agent-executor/codex/control-
|
|
1606
|
+
// src/agent-executor/codex/control-read-methods.ts
|
|
1488
1607
|
function assertOptionalItemsCursor(cursor, caller) {
|
|
1489
|
-
if (cursor === undefined)
|
|
1608
|
+
if (cursor === undefined || cursor === null || cursor === "")
|
|
1490
1609
|
return;
|
|
1491
1610
|
if (typeof cursor === "string") {
|
|
1492
1611
|
if (cursor.trim().length === 0) {
|
|
1493
|
-
throw new TypeError(`[stitchkit] ${caller}: cursor
|
|
1612
|
+
throw new TypeError(`[stitchkit] ${caller}: item cursor cannot be whitespace-only`);
|
|
1494
1613
|
}
|
|
1495
1614
|
return;
|
|
1496
1615
|
}
|
|
1497
|
-
if (typeof cursor !== "object" || cursor
|
|
1616
|
+
if (typeof cursor !== "object" || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
|
|
1498
1617
|
throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
|
|
1499
1618
|
}
|
|
1500
1619
|
}
|
|
1501
|
-
function
|
|
1502
|
-
const call = async (method, params) => {
|
|
1503
|
-
input.ensureAlive();
|
|
1504
|
-
return input.peer.request(method, params);
|
|
1505
|
-
};
|
|
1620
|
+
function createCodexReadMethods(call) {
|
|
1506
1621
|
return {
|
|
1507
|
-
readConfig(params) {
|
|
1508
|
-
return call("config/read", {
|
|
1622
|
+
async readConfig(params, rpcOptions) {
|
|
1623
|
+
return parseCodexResponse("config/read", CodexConfigReadResponseSchema, await call("config/read", {
|
|
1509
1624
|
...params?.cwd !== undefined && { cwd: params.cwd },
|
|
1510
|
-
...params?.includeLayers !== undefined && {
|
|
1511
|
-
|
|
1625
|
+
...params?.includeLayers !== undefined && {
|
|
1626
|
+
includeLayers: params.includeLayers
|
|
1627
|
+
}
|
|
1628
|
+
}, rpcOptions));
|
|
1512
1629
|
},
|
|
1513
|
-
async readThread(params) {
|
|
1630
|
+
async readThread(params, rpcOptions) {
|
|
1514
1631
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
|
|
1515
|
-
return call("thread/read", {
|
|
1632
|
+
return parseCodexResponse("thread/read", CodexReadThreadResponseSchema, await call("thread/read", {
|
|
1516
1633
|
threadId,
|
|
1517
1634
|
...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
|
|
1518
|
-
});
|
|
1635
|
+
}, rpcOptions));
|
|
1519
1636
|
},
|
|
1520
|
-
listCollaborationModes() {
|
|
1521
|
-
return call("collaborationMode/list", {});
|
|
1637
|
+
async listCollaborationModes(rpcOptions) {
|
|
1638
|
+
return parseCodexResponse("collaborationMode/list", CodexCollaborationModesResponseSchema, await call("collaborationMode/list", {}, rpcOptions));
|
|
1522
1639
|
},
|
|
1523
|
-
async listTurns(params) {
|
|
1524
|
-
const
|
|
1525
|
-
|
|
1526
|
-
|
|
1640
|
+
async listTurns(params, rpcOptions) {
|
|
1641
|
+
const caller = "CodexControlClient.listTurns";
|
|
1642
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1643
|
+
assertOptionalLimit(params.limit, caller);
|
|
1644
|
+
if (params.cursor !== undefined && params.cursor !== null && typeof params.cursor !== "string") {
|
|
1645
|
+
throw new TypeError(`[stitchkit] ${caller}: cursor must be a string or null`);
|
|
1646
|
+
}
|
|
1647
|
+
return parseCodexResponse("thread/turns/list", CodexTurnsPageSchema2, await call("thread/turns/list", {
|
|
1527
1648
|
threadId,
|
|
1528
1649
|
...params.cursor !== undefined && { cursor: params.cursor },
|
|
1529
1650
|
...params.limit !== undefined && { limit: params.limit },
|
|
1530
1651
|
...params.itemsView !== undefined && { itemsView: params.itemsView },
|
|
1531
1652
|
...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
|
|
1532
|
-
});
|
|
1653
|
+
}, rpcOptions));
|
|
1533
1654
|
},
|
|
1534
|
-
async listItems(params) {
|
|
1535
|
-
const
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1655
|
+
async listItems(params, rpcOptions) {
|
|
1656
|
+
const caller = "CodexControlClient.listItems";
|
|
1657
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1658
|
+
assertOptionalLimit(params.limit, caller);
|
|
1659
|
+
assertOptionalNonEmptyString(params.turnId, "turnId", caller);
|
|
1660
|
+
assertOptionalItemsCursor(params.cursor, caller);
|
|
1661
|
+
return parseCodexResponse("thread/items/list", CodexItemsPageSchema, await call("thread/items/list", {
|
|
1540
1662
|
threadId,
|
|
1541
1663
|
...params.turnId !== undefined && { turnId: params.turnId },
|
|
1542
1664
|
...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
|
|
@@ -1545,435 +1667,356 @@ function createCodexControlClient(input) {
|
|
|
1545
1667
|
...params.deferOutput !== undefined && {
|
|
1546
1668
|
deferOutput: safeJsonValue(params.deferOutput)
|
|
1547
1669
|
}
|
|
1548
|
-
});
|
|
1670
|
+
}, rpcOptions));
|
|
1549
1671
|
},
|
|
1550
|
-
listMcpServerStatus(params) {
|
|
1551
|
-
return call("mcpServerStatus/list", {
|
|
1672
|
+
async listMcpServerStatus(params, rpcOptions) {
|
|
1673
|
+
return parseCodexResponse("mcpServerStatus/list", CodexMcpServerStatusPageSchema, await call("mcpServerStatus/list", {
|
|
1552
1674
|
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1553
1675
|
...params?.limit !== undefined && { limit: params.limit },
|
|
1554
1676
|
...params?.threadId !== undefined && { threadId: params.threadId },
|
|
1555
1677
|
...params?.serverName !== undefined && { serverName: params.serverName },
|
|
1556
1678
|
...params?.detail !== undefined && { detail: params.detail }
|
|
1557
|
-
});
|
|
1679
|
+
}, rpcOptions));
|
|
1558
1680
|
},
|
|
1559
|
-
listSkills(params) {
|
|
1560
|
-
return call("skills/list", {
|
|
1681
|
+
async listSkills(params, rpcOptions) {
|
|
1682
|
+
return parseCodexResponse("skills/list", CodexSkillsListResponseSchema, await call("skills/list", {
|
|
1561
1683
|
...params?.cwds !== undefined && { cwds: [...params.cwds] },
|
|
1562
1684
|
...params?.forceReload !== undefined && { forceReload: params.forceReload }
|
|
1563
|
-
});
|
|
1685
|
+
}, rpcOptions));
|
|
1564
1686
|
},
|
|
1565
|
-
listModels(params) {
|
|
1566
|
-
return call("model/list", {
|
|
1687
|
+
async listModels(params, rpcOptions) {
|
|
1688
|
+
return parseCodexResponse("model/list", CodexModelsPageSchema, await call("model/list", {
|
|
1567
1689
|
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1568
1690
|
...params?.limit !== undefined && { limit: params.limit },
|
|
1569
|
-
...params?.includeHidden !== undefined && {
|
|
1570
|
-
|
|
1571
|
-
|
|
1691
|
+
...params?.includeHidden !== undefined && {
|
|
1692
|
+
includeHidden: params.includeHidden
|
|
1693
|
+
},
|
|
1694
|
+
...params?.modelProvider !== undefined && {
|
|
1695
|
+
modelProvider: params.modelProvider
|
|
1696
|
+
}
|
|
1697
|
+
}, rpcOptions));
|
|
1572
1698
|
},
|
|
1573
|
-
readAccount(params) {
|
|
1574
|
-
return call("account/read", {
|
|
1699
|
+
async readAccount(params, rpcOptions) {
|
|
1700
|
+
return parseCodexResponse("account/read", CodexAccountReadResponseSchema, await call("account/read", {
|
|
1575
1701
|
...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
|
|
1576
|
-
});
|
|
1702
|
+
}, rpcOptions));
|
|
1577
1703
|
},
|
|
1578
|
-
readRateLimits() {
|
|
1579
|
-
return call("account/rateLimits/read");
|
|
1580
|
-
}
|
|
1581
|
-
...createCodexThreadControlMethods(call)
|
|
1704
|
+
async readRateLimits(rpcOptions) {
|
|
1705
|
+
return parseCodexResponse("account/rateLimits/read", CodexRateLimitsResponseSchema, await call("account/rateLimits/read", undefined, rpcOptions));
|
|
1706
|
+
}
|
|
1582
1707
|
};
|
|
1583
1708
|
}
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
});
|
|
1609
|
-
},
|
|
1610
|
-
injectItems(params) {
|
|
1611
|
-
return controlClient.injectItems({
|
|
1612
|
-
...params,
|
|
1613
|
-
threadId: params.threadId ?? threadId
|
|
1614
|
-
});
|
|
1615
|
-
},
|
|
1616
|
-
unsubscribeThread(params) {
|
|
1617
|
-
return controlClient.unsubscribeThread({
|
|
1618
|
-
threadId: params?.threadId ?? threadId
|
|
1619
|
-
});
|
|
1620
|
-
},
|
|
1621
|
-
archiveThread(params) {
|
|
1622
|
-
return controlClient.archiveThread({
|
|
1623
|
-
threadId: params?.threadId ?? threadId
|
|
1624
|
-
});
|
|
1625
|
-
},
|
|
1626
|
-
unarchiveThread(params) {
|
|
1627
|
-
return controlClient.unarchiveThread({
|
|
1628
|
-
threadId: params?.threadId ?? threadId
|
|
1629
|
-
});
|
|
1630
|
-
},
|
|
1631
|
-
updateThreadMetadata(params) {
|
|
1632
|
-
return controlClient.updateThreadMetadata({
|
|
1633
|
-
...params,
|
|
1634
|
-
threadId: params?.threadId ?? threadId
|
|
1635
|
-
});
|
|
1636
|
-
},
|
|
1637
|
-
setThreadName(params) {
|
|
1638
|
-
return controlClient.setThreadName({
|
|
1639
|
-
...params,
|
|
1640
|
-
threadId: params.threadId ?? threadId
|
|
1641
|
-
});
|
|
1709
|
+
|
|
1710
|
+
// src/agent-executor/codex/turn-input.ts
|
|
1711
|
+
import { isAbsolute } from "node:path";
|
|
1712
|
+
import { z as z3 } from "zod";
|
|
1713
|
+
var NonEmptyNoNulStringSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00"), {
|
|
1714
|
+
message: "must be a non-empty string without NUL bytes"
|
|
1715
|
+
});
|
|
1716
|
+
var AbsolutePathNoNulSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00") && isAbsolute(value), {
|
|
1717
|
+
message: "must be an absolute path without NUL bytes"
|
|
1718
|
+
});
|
|
1719
|
+
var CodexSkillInputSchema = z3.strictObject({
|
|
1720
|
+
type: z3.literal("skill"),
|
|
1721
|
+
name: NonEmptyNoNulStringSchema,
|
|
1722
|
+
path: NonEmptyNoNulStringSchema
|
|
1723
|
+
});
|
|
1724
|
+
var CodexLocalImageInputSchema = z3.strictObject({
|
|
1725
|
+
type: z3.literal("localImage"),
|
|
1726
|
+
path: AbsolutePathNoNulSchema
|
|
1727
|
+
});
|
|
1728
|
+
function validateCodexExtraInput(part) {
|
|
1729
|
+
if (part.type === "skill") {
|
|
1730
|
+
const parsed = CodexSkillInputSchema.safeParse(part);
|
|
1731
|
+
if (!parsed.success) {
|
|
1732
|
+
throw new TypeError("Codex skill input name and path must be non-empty strings without NUL bytes");
|
|
1642
1733
|
}
|
|
1643
|
-
|
|
1734
|
+
return { type: "skill", name: parsed.data.name, path: parsed.data.path };
|
|
1735
|
+
}
|
|
1736
|
+
if (part.type === "localImage") {
|
|
1737
|
+
const parsed = CodexLocalImageInputSchema.safeParse(part);
|
|
1738
|
+
if (!parsed.success) {
|
|
1739
|
+
throw new TypeError("Codex localImage input path must be an absolute path without NUL bytes");
|
|
1740
|
+
}
|
|
1741
|
+
return { type: "localImage", path: parsed.data.path };
|
|
1742
|
+
}
|
|
1743
|
+
return;
|
|
1644
1744
|
}
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
"
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
"functionCallOutput"
|
|
1659
|
-
]);
|
|
1660
|
-
var STATUSLESS_TOOL_ITEMS = new Set([
|
|
1661
|
-
"webSearch",
|
|
1662
|
-
"imageView",
|
|
1663
|
-
"sleep",
|
|
1664
|
-
"functionCallOutput"
|
|
1665
|
-
]);
|
|
1666
|
-
var CODEX_CONTENT_ITEMS = new Set([
|
|
1667
|
-
"agentMessage",
|
|
1668
|
-
"reasoning",
|
|
1669
|
-
"userMessage",
|
|
1670
|
-
"plan",
|
|
1671
|
-
"contextCompaction",
|
|
1672
|
-
"hookPrompt",
|
|
1673
|
-
"subAgentActivity",
|
|
1674
|
-
"enteredReviewMode",
|
|
1675
|
-
"exitedReviewMode"
|
|
1676
|
-
]);
|
|
1677
|
-
var KNOWN_CODEX_ERROR_CODES = new Set([
|
|
1678
|
-
"contextWindowExceeded",
|
|
1679
|
-
"sessionBudgetExceeded",
|
|
1680
|
-
"usageLimitExceeded",
|
|
1681
|
-
"rateLimitExceeded",
|
|
1682
|
-
"flexUnavailable",
|
|
1683
|
-
"serverOverloaded",
|
|
1684
|
-
"modelNotFound",
|
|
1685
|
-
"policyCapacityUnavailable",
|
|
1686
|
-
"cyberPolicy",
|
|
1687
|
-
"bioPolicy",
|
|
1688
|
-
"misalignmentPolicyViolation",
|
|
1689
|
-
"tooManyDenials",
|
|
1690
|
-
"internalServerError",
|
|
1691
|
-
"unauthorized",
|
|
1692
|
-
"badRequest",
|
|
1693
|
-
"threadRollbackFailed",
|
|
1694
|
-
"sandboxError",
|
|
1695
|
-
"other",
|
|
1696
|
-
"inferenceHookDenied"
|
|
1697
|
-
]);
|
|
1698
|
-
var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
|
|
1699
|
-
"httpConnectionFailed",
|
|
1700
|
-
"responseStreamConnectionFailed",
|
|
1701
|
-
"responseStreamDisconnected",
|
|
1702
|
-
"responseTooManyFailedAttempts",
|
|
1703
|
-
"activeTurnNotSteerable"
|
|
1704
|
-
]);
|
|
1705
|
-
var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
|
|
1706
|
-
function toolName(item) {
|
|
1707
|
-
if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
|
|
1708
|
-
return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
|
|
1745
|
+
function inlineCodexParts(parts, options) {
|
|
1746
|
+
return inlineOrderedParts(parts, {
|
|
1747
|
+
...options,
|
|
1748
|
+
acceptedDescription: "text, images, local images, and skills",
|
|
1749
|
+
validateExtra: validateCodexExtraInput
|
|
1750
|
+
});
|
|
1751
|
+
}
|
|
1752
|
+
function codexTurnInput(parts) {
|
|
1753
|
+
if (parts.every((part) => part.type === "text")) {
|
|
1754
|
+
return [
|
|
1755
|
+
{ type: "text", text: parts.map((part) => part.text).join(`
|
|
1756
|
+
`), text_elements: [] }
|
|
1757
|
+
];
|
|
1709
1758
|
}
|
|
1710
|
-
|
|
1711
|
-
|
|
1759
|
+
const out = [];
|
|
1760
|
+
for (const part of parts) {
|
|
1761
|
+
if (part.type === "text") {
|
|
1762
|
+
out.push({ type: "text", text: part.text, text_elements: [] });
|
|
1763
|
+
} else if (part.type === "skill") {
|
|
1764
|
+
out.push({ type: "skill", name: part.name, path: part.path });
|
|
1765
|
+
} else if (part.type === "localImage") {
|
|
1766
|
+
out.push({ type: "localImage", path: part.path });
|
|
1767
|
+
} else {
|
|
1768
|
+
out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
|
|
1769
|
+
}
|
|
1712
1770
|
}
|
|
1713
|
-
return
|
|
1771
|
+
return out;
|
|
1714
1772
|
}
|
|
1715
|
-
function
|
|
1716
|
-
const
|
|
1717
|
-
|
|
1773
|
+
async function sendCodexTurnSteer(peer, params, rpcOptions) {
|
|
1774
|
+
const steered = parseCodexResponse("turn/steer", CodexTurnSteerResponseSchema, await peer.request("turn/steer", {
|
|
1775
|
+
threadId: params.threadId,
|
|
1776
|
+
expectedTurnId: params.expectedTurnId,
|
|
1777
|
+
input: codexTurnInput(params.parts),
|
|
1778
|
+
...params.clientId !== undefined && { clientUserMessageId: params.clientId }
|
|
1779
|
+
}, rpcOptions));
|
|
1780
|
+
return { turnId: steered.turnId };
|
|
1718
1781
|
}
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
if (
|
|
1723
|
-
|
|
1724
|
-
return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
|
|
1782
|
+
|
|
1783
|
+
// src/agent-executor/codex/session-controls.ts
|
|
1784
|
+
function validateCodexForkBounds(options, caller) {
|
|
1785
|
+
if (options.beforeTurnId !== undefined && options.lastTurnId !== undefined) {
|
|
1786
|
+
throw new TypeError(`[stitchkit] ${caller}: beforeTurnId and lastTurnId are mutually exclusive`);
|
|
1725
1787
|
}
|
|
1726
|
-
return false;
|
|
1727
1788
|
}
|
|
1728
|
-
function
|
|
1729
|
-
if (
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1789
|
+
function validateCodexPolicyOverrides(overrides, caller) {
|
|
1790
|
+
if (overrides.runtimeWorkspaceRoots !== undefined) {
|
|
1791
|
+
if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
|
|
1792
|
+
throw new TypeError(`[stitchkit] ${caller}: runtimeWorkspaceRoots must be an array of strings`);
|
|
1793
|
+
}
|
|
1794
|
+
for (const root of overrides.runtimeWorkspaceRoots) {
|
|
1795
|
+
if (typeof root !== "string" || root.trim().length === 0) {
|
|
1796
|
+
throw new TypeError(`[stitchkit] ${caller}: every runtimeWorkspaceRoots entry must be a non-empty string`);
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1734
1799
|
}
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
} catch {
|
|
1741
|
-
return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
|
|
1800
|
+
if (overrides.config !== undefined) {
|
|
1801
|
+
if (typeof overrides.config !== "object" || overrides.config === null || Array.isArray(overrides.config)) {
|
|
1802
|
+
throw new TypeError(`[stitchkit] ${caller}: config must be a plain JSON object`);
|
|
1803
|
+
}
|
|
1804
|
+
safeJsonValue(overrides.config);
|
|
1742
1805
|
}
|
|
1743
1806
|
}
|
|
1744
|
-
function
|
|
1745
|
-
const
|
|
1746
|
-
const
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1807
|
+
function buildCodexThreadPolicyParams(base, overrides) {
|
|
1808
|
+
const mergedConfig = base.config !== undefined || overrides?.config !== undefined ? { ...base.config ?? {}, ...overrides?.config ?? {} } : undefined;
|
|
1809
|
+
const merged = {
|
|
1810
|
+
...base,
|
|
1811
|
+
...overrides,
|
|
1812
|
+
...mergedConfig !== undefined && { config: mergedConfig }
|
|
1813
|
+
};
|
|
1814
|
+
validateCodexPolicyOverrides(merged, "CodexSession");
|
|
1815
|
+
const params = {};
|
|
1816
|
+
if (merged.model !== undefined)
|
|
1817
|
+
params.model = merged.model;
|
|
1818
|
+
if (merged.modelProvider !== undefined)
|
|
1819
|
+
params.modelProvider = merged.modelProvider;
|
|
1820
|
+
if (merged.approvalPolicy !== undefined)
|
|
1821
|
+
params.approvalPolicy = safeJsonValue(merged.approvalPolicy);
|
|
1822
|
+
if (merged.sandbox !== undefined)
|
|
1823
|
+
params.sandbox = merged.sandbox;
|
|
1824
|
+
if (merged.developerInstructions !== undefined)
|
|
1825
|
+
params.developerInstructions = merged.developerInstructions;
|
|
1826
|
+
if (merged.runtimeWorkspaceRoots !== undefined)
|
|
1827
|
+
params.runtimeWorkspaceRoots = [...merged.runtimeWorkspaceRoots];
|
|
1828
|
+
if (merged.config !== undefined)
|
|
1829
|
+
params.config = safeJsonValue(merged.config);
|
|
1830
|
+
return params;
|
|
1831
|
+
}
|
|
1832
|
+
function validateCodexTurnStartOverrides(caller, turnInput, activeModelProvider) {
|
|
1833
|
+
assertRequiredNonEmptyString(turnInput.clientId, "clientId", caller);
|
|
1834
|
+
assertOptionalNonEmptyNoNulString(turnInput.cwd, "cwd", caller);
|
|
1835
|
+
if (turnInput.modelProvider !== undefined) {
|
|
1836
|
+
if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
|
|
1837
|
+
throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
|
|
1751
1838
|
}
|
|
1752
|
-
return rawMessage;
|
|
1753
1839
|
}
|
|
1754
|
-
if (
|
|
1755
|
-
|
|
1840
|
+
if (turnInput.collaborationMode !== undefined) {
|
|
1841
|
+
CodexCollaborationModeSchema2.parse(turnInput.collaborationMode);
|
|
1756
1842
|
}
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
if (
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
const found = httpStatusOf(nested, depth + 1);
|
|
1767
|
-
if (found !== undefined)
|
|
1768
|
-
return found;
|
|
1843
|
+
if (turnInput.approvalPolicy !== undefined) {
|
|
1844
|
+
CodexApprovalPolicySchema2.parse(turnInput.approvalPolicy);
|
|
1845
|
+
}
|
|
1846
|
+
if (turnInput.sandboxPolicy !== undefined) {
|
|
1847
|
+
CodexSandboxPolicySchema2.parse(turnInput.sandboxPolicy);
|
|
1848
|
+
safeJsonValue(turnInput.sandboxPolicy);
|
|
1849
|
+
}
|
|
1850
|
+
if (turnInput.runtimeWorkspaceRoots !== undefined) {
|
|
1851
|
+
validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, caller);
|
|
1769
1852
|
}
|
|
1770
|
-
return;
|
|
1771
|
-
}
|
|
1772
|
-
function failureKind(info) {
|
|
1773
|
-
if (info === "unauthorized")
|
|
1774
|
-
return "authRequired";
|
|
1775
|
-
if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "sessionBudgetExceeded")
|
|
1776
|
-
return "rateLimited";
|
|
1777
|
-
const status = httpStatusOf(info);
|
|
1778
|
-
if (status === 401 || status === 403)
|
|
1779
|
-
return "authRequired";
|
|
1780
|
-
if (status === 429)
|
|
1781
|
-
return "rateLimited";
|
|
1782
|
-
return "restartRecommended";
|
|
1783
1853
|
}
|
|
1784
|
-
function
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
...rawTotals.cachedInputTokens !== undefined && {
|
|
1791
|
-
cachedInputTokens: rawTotals.cachedInputTokens
|
|
1792
|
-
},
|
|
1793
|
-
...rawTotals.cacheWriteInputTokens !== undefined && {
|
|
1794
|
-
cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
|
|
1795
|
-
},
|
|
1796
|
-
...rawTotals.reasoningOutputTokens !== undefined && {
|
|
1797
|
-
thinkingTokens: rawTotals.reasoningOutputTokens
|
|
1798
|
-
},
|
|
1799
|
-
...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
|
|
1854
|
+
function buildCodexTurnStartRpcParams(caller, threadId, turnInput, parts, activeModelProvider) {
|
|
1855
|
+
validateCodexTurnStartOverrides(caller, turnInput, activeModelProvider);
|
|
1856
|
+
const params = {
|
|
1857
|
+
threadId,
|
|
1858
|
+
input: codexTurnInput(parts),
|
|
1859
|
+
clientUserMessageId: turnInput.clientId
|
|
1800
1860
|
};
|
|
1801
|
-
|
|
1861
|
+
if (turnInput.cwd !== undefined)
|
|
1862
|
+
params.cwd = turnInput.cwd;
|
|
1863
|
+
if (turnInput.model !== undefined)
|
|
1864
|
+
params.model = turnInput.model;
|
|
1865
|
+
if (turnInput.reasoningEffort !== undefined)
|
|
1866
|
+
params.effort = turnInput.reasoningEffort;
|
|
1867
|
+
if (turnInput.collaborationMode !== undefined) {
|
|
1868
|
+
params.collaborationMode = CodexCollaborationModeSchema2.parse(turnInput.collaborationMode);
|
|
1869
|
+
}
|
|
1870
|
+
if (turnInput.approvalPolicy !== undefined) {
|
|
1871
|
+
params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
|
|
1872
|
+
}
|
|
1873
|
+
if (turnInput.sandboxPolicy !== undefined) {
|
|
1874
|
+
params.sandboxPolicy = safeJsonValue(turnInput.sandboxPolicy);
|
|
1875
|
+
}
|
|
1876
|
+
if (turnInput.runtimeWorkspaceRoots !== undefined) {
|
|
1877
|
+
params.runtimeWorkspaceRoots = [...turnInput.runtimeWorkspaceRoots];
|
|
1878
|
+
}
|
|
1879
|
+
return params;
|
|
1802
1880
|
}
|
|
1803
|
-
function
|
|
1804
|
-
const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
|
|
1805
|
-
const normalizedTotal = normalizeCodexTokenTotals(total);
|
|
1881
|
+
function createCodexSessionMutators(input) {
|
|
1806
1882
|
return {
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
};
|
|
1830
|
-
}
|
|
1831
|
-
function classifyCodexNotification(method, params, state) {
|
|
1832
|
-
const base = { turnId: state.turnId };
|
|
1833
|
-
switch (method) {
|
|
1834
|
-
case "item/agentMessage/delta": {
|
|
1835
|
-
const p = CodexNotificationParams[method].parse(params);
|
|
1836
|
-
return {
|
|
1837
|
-
kind: "deltas",
|
|
1838
|
-
deltas: [{ type: "text", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }]
|
|
1839
|
-
};
|
|
1840
|
-
}
|
|
1841
|
-
case "item/reasoning/textDelta":
|
|
1842
|
-
case "item/reasoning/summaryTextDelta": {
|
|
1843
|
-
const p = CodexNotificationParams[method].parse(params);
|
|
1844
|
-
return {
|
|
1845
|
-
kind: "deltas",
|
|
1846
|
-
deltas: [
|
|
1847
|
-
{ type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
|
|
1848
|
-
]
|
|
1849
|
-
};
|
|
1850
|
-
}
|
|
1851
|
-
case "item/started":
|
|
1852
|
-
case "item/completed": {
|
|
1853
|
-
const { item } = CodexNotificationParams[method].parse(params);
|
|
1854
|
-
if (CODEX_CONTENT_ITEMS.has(item.type))
|
|
1855
|
-
return { kind: "ignore", reason: `${method} ${item.type}` };
|
|
1856
|
-
if (!CODEX_TOOL_ITEMS.has(item.type)) {
|
|
1857
|
-
return {
|
|
1858
|
-
kind: "unhandled",
|
|
1859
|
-
delta: {
|
|
1860
|
-
type: "error",
|
|
1861
|
-
...base,
|
|
1862
|
-
itemId: `unhandled:${item.id}`,
|
|
1863
|
-
raw: raw(`${method}/${item.type}`),
|
|
1864
|
-
kind: "unhandled",
|
|
1865
|
-
message: `Codex item ${item.type} is not known to this driver`
|
|
1866
|
-
}
|
|
1867
|
-
};
|
|
1883
|
+
async steerTurn(steerInput, rpcOptions) {
|
|
1884
|
+
input.ensureAlive();
|
|
1885
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1886
|
+
const caller = "CodexSession.steerTurn";
|
|
1887
|
+
const targetThreadId = steerInput.threadId === undefined ? input.threadId : assertNonEmptyThreadId(steerInput.threadId, caller);
|
|
1888
|
+
assertOptionalNonEmptyString(steerInput.clientId, "clientId", caller);
|
|
1889
|
+
assertOptionalNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
|
|
1890
|
+
if (targetThreadId !== input.threadId) {
|
|
1891
|
+
const expectedTurnId = assertRequiredNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
|
|
1892
|
+
const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(steerInput.input, {
|
|
1893
|
+
...input.imageOptions,
|
|
1894
|
+
driverLabel: "The Codex driver",
|
|
1895
|
+
signal
|
|
1896
|
+
}));
|
|
1897
|
+
input.ensureAlive();
|
|
1898
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1899
|
+
return sendCodexTurnSteer(input.peer, {
|
|
1900
|
+
threadId: targetThreadId,
|
|
1901
|
+
expectedTurnId,
|
|
1902
|
+
parts,
|
|
1903
|
+
...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
|
|
1904
|
+
}, rpcOptions);
|
|
1868
1905
|
}
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1906
|
+
const active = input.getActiveTurn();
|
|
1907
|
+
let expectedTurnId;
|
|
1908
|
+
if (active !== undefined) {
|
|
1909
|
+
if (active.codexTurnId === undefined) {
|
|
1910
|
+
throw new Error("Cannot steer turn: no Codex turn is currently running");
|
|
1911
|
+
}
|
|
1912
|
+
if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== active.codexTurnId) {
|
|
1913
|
+
throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${active.codexTurnId}`);
|
|
1914
|
+
}
|
|
1915
|
+
expectedTurnId = active.codexTurnId;
|
|
1916
|
+
} else {
|
|
1917
|
+
if (steerInput.expectedTurnId === undefined) {
|
|
1918
|
+
throw new Error("Cannot steer turn: no Codex turn is currently running");
|
|
1919
|
+
}
|
|
1920
|
+
expectedTurnId = steerInput.expectedTurnId;
|
|
1884
1921
|
}
|
|
1885
|
-
const
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
toolName: toolName(item),
|
|
1900
|
-
outcome,
|
|
1901
|
-
...output !== undefined && output !== null && {
|
|
1902
|
-
output: safeJsonValue(output)
|
|
1903
|
-
}
|
|
1904
|
-
}
|
|
1905
|
-
]
|
|
1906
|
-
};
|
|
1907
|
-
}
|
|
1908
|
-
case "turn/completed": {
|
|
1909
|
-
const { turn } = CodexNotificationParams[method].parse(params);
|
|
1910
|
-
const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
|
|
1911
|
-
const deltas = [];
|
|
1912
|
-
if (outcome === "failed") {
|
|
1913
|
-
deltas.push({
|
|
1914
|
-
type: "error",
|
|
1915
|
-
...base,
|
|
1916
|
-
itemId: "failure",
|
|
1917
|
-
raw: raw(method),
|
|
1918
|
-
kind: failureKind(turn.error?.codexErrorInfo),
|
|
1919
|
-
message: codexFailureMessage(turn)
|
|
1920
|
-
});
|
|
1922
|
+
const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(steerInput.input, {
|
|
1923
|
+
...input.imageOptions,
|
|
1924
|
+
driverLabel: "The Codex driver",
|
|
1925
|
+
signal
|
|
1926
|
+
}));
|
|
1927
|
+
input.ensureAlive();
|
|
1928
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1929
|
+
const afterAwait = input.getActiveTurn();
|
|
1930
|
+
if (active !== undefined) {
|
|
1931
|
+
if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
|
|
1932
|
+
throw new Error("Cannot steer turn: the active Codex turn ended before steering was sent");
|
|
1933
|
+
}
|
|
1934
|
+
} else if (afterAwait !== undefined && afterAwait.codexTurnId !== expectedTurnId) {
|
|
1935
|
+
throw new TypeError(`Expected active Codex turn ${expectedTurnId}, but current turn is ${afterAwait.codexTurnId ?? "starting"}`);
|
|
1921
1936
|
}
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
const
|
|
1937
|
+
return sendCodexTurnSteer(input.peer, {
|
|
1938
|
+
threadId: input.threadId,
|
|
1939
|
+
expectedTurnId,
|
|
1940
|
+
parts,
|
|
1941
|
+
...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
|
|
1942
|
+
}, rpcOptions);
|
|
1943
|
+
},
|
|
1944
|
+
async forkThread(options = {}, rpcOptions) {
|
|
1945
|
+
input.ensureAlive();
|
|
1946
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1947
|
+
validateCodexForkBounds(options, "CodexSession.forkThread");
|
|
1948
|
+
const policyParams = buildCodexThreadPolicyParams({}, options);
|
|
1949
|
+
const forked = parseCodexResponse("thread/fork", CodexStartedThreadSchema, await input.peer.request("thread/fork", {
|
|
1950
|
+
threadId: input.threadId,
|
|
1951
|
+
...policyParams,
|
|
1952
|
+
...options.cwd !== undefined && { cwd: options.cwd },
|
|
1953
|
+
...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
|
|
1954
|
+
...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
|
|
1955
|
+
...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns },
|
|
1956
|
+
...options.deferGoalContinuation !== undefined && {
|
|
1957
|
+
deferGoalContinuation: options.deferGoalContinuation
|
|
1958
|
+
}
|
|
1959
|
+
}, rpcOptions));
|
|
1934
1960
|
return {
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
rateLimits: parsed.rateLimits,
|
|
1938
|
-
rateLimitsByLimitId: parsed.rateLimitsByLimitId
|
|
1939
|
-
} : parsed.rateLimits
|
|
1961
|
+
nativeThreadId: forked.thread.id,
|
|
1962
|
+
threadContext: extractCodexThreadContext(forked)
|
|
1940
1963
|
};
|
|
1941
1964
|
}
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
// src/agent-executor/codex/event-routing.ts
|
|
1969
|
+
function field(object, key) {
|
|
1970
|
+
return isRecord(object) ? nonEmptyString(object[key]) : undefined;
|
|
1971
|
+
}
|
|
1972
|
+
function codexThreadIdOf(params) {
|
|
1973
|
+
if (!isRecord(params))
|
|
1974
|
+
return;
|
|
1975
|
+
return field(params, "threadId") ?? field(params.thread, "id") ?? field(params.turn, "threadId") ?? field(params.item, "threadId");
|
|
1976
|
+
}
|
|
1977
|
+
function codexTurnIdOf(params) {
|
|
1978
|
+
if (!isRecord(params))
|
|
1979
|
+
return;
|
|
1980
|
+
return field(params, "turnId") ?? field(params.turn, "id") ?? field(params.item, "turnId");
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
class CodexStartingTurn {
|
|
1984
|
+
waiting = [];
|
|
1985
|
+
bytes = 0;
|
|
1986
|
+
failure;
|
|
1987
|
+
defer(params, deliver) {
|
|
1988
|
+
if (this.failure !== undefined)
|
|
1989
|
+
throw this.failure;
|
|
1990
|
+
this.bytes += JSON.stringify(params ?? null).length;
|
|
1991
|
+
if (this.waiting.length >= TURN_QUEUE.maxItems || this.bytes > TURN_QUEUE.maxBytes) {
|
|
1992
|
+
this.failure = new Error("Codex events before turn/start exceeded the turn queue limit");
|
|
1993
|
+
throw this.failure;
|
|
1994
|
+
}
|
|
1995
|
+
this.waiting.push(deliver);
|
|
1996
|
+
}
|
|
1997
|
+
flush() {
|
|
1998
|
+
for (const deliver of this.waiting.splice(0))
|
|
1999
|
+
deliver();
|
|
2000
|
+
if (this.failure !== undefined)
|
|
2001
|
+
throw this.failure;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
function codexEventTurn(current, params) {
|
|
2005
|
+
if (current === undefined)
|
|
2006
|
+
return;
|
|
2007
|
+
const threadId = codexThreadIdOf(params);
|
|
2008
|
+
if (threadId !== undefined && current.threadId !== undefined && threadId !== current.threadId)
|
|
2009
|
+
return;
|
|
2010
|
+
const turnId = codexTurnIdOf(params);
|
|
2011
|
+
if (turnId !== undefined && current.codexTurnId !== undefined && turnId !== current.codexTurnId)
|
|
2012
|
+
return;
|
|
2013
|
+
return current;
|
|
1957
2014
|
}
|
|
1958
2015
|
|
|
1959
2016
|
// src/agent-executor/codex/request-answers.ts
|
|
1960
2017
|
function isKnownCodexRequestMethod(method) {
|
|
1961
2018
|
return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
|
|
1962
2019
|
}
|
|
1963
|
-
function externalCodexTurnIdOf(params) {
|
|
1964
|
-
if (typeof params !== "object" || params === null)
|
|
1965
|
-
return "external";
|
|
1966
|
-
const direct = nonEmptyString(Reflect.get(params, "turnId"));
|
|
1967
|
-
if (direct !== undefined)
|
|
1968
|
-
return direct;
|
|
1969
|
-
const turn = Reflect.get(params, "turn");
|
|
1970
|
-
if (typeof turn === "object" && turn !== null) {
|
|
1971
|
-
const nested = nonEmptyString(Reflect.get(turn, "id"));
|
|
1972
|
-
if (nested !== undefined)
|
|
1973
|
-
return nested;
|
|
1974
|
-
}
|
|
1975
|
-
return "external";
|
|
1976
|
-
}
|
|
1977
2020
|
function parseCodexApprovalRequest(method, params) {
|
|
1978
2021
|
const asked = CodexApprovalParamsSchema.parse(params);
|
|
1979
2022
|
const callId = nonEmptyString(asked.itemId);
|
|
@@ -2009,202 +2052,650 @@ function parseCodexApprovalRequest(method, params) {
|
|
|
2009
2052
|
...typeof asked.command === "string" && { prompt: asked.command },
|
|
2010
2053
|
...input !== undefined && { input }
|
|
2011
2054
|
}
|
|
2012
|
-
};
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
function parseCodexInputRequest(params) {
|
|
2058
|
+
const asked = CodexUserInputParamsSchema.parse(params);
|
|
2059
|
+
const callId = nonEmptyString(asked.itemId);
|
|
2060
|
+
const questions = asked.questions.map((question) => ({
|
|
2061
|
+
id: question.id,
|
|
2062
|
+
header: question.header,
|
|
2063
|
+
question: question.question,
|
|
2064
|
+
...question.options !== undefined && {
|
|
2065
|
+
options: question.options === null ? null : question.options.map((option) => ({
|
|
2066
|
+
label: option.label,
|
|
2067
|
+
description: option.description
|
|
2068
|
+
}))
|
|
2069
|
+
},
|
|
2070
|
+
...question.isOther !== undefined && { isOther: question.isOther },
|
|
2071
|
+
...question.isSecret !== undefined && { isSecret: question.isSecret }
|
|
2072
|
+
}));
|
|
2073
|
+
const detail = { method: CODEX_INPUT_REQUEST };
|
|
2074
|
+
return {
|
|
2075
|
+
detail,
|
|
2076
|
+
deltaFields: {
|
|
2077
|
+
...callId !== undefined && { callId },
|
|
2078
|
+
input: safeJsonValue(questions)
|
|
2079
|
+
}
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
function parseCodexPermissionsRequest(params) {
|
|
2083
|
+
const asked = CodexPermissionsApprovalParamsSchema.parse(params);
|
|
2084
|
+
const callId = nonEmptyString(asked.itemId);
|
|
2085
|
+
const permissions = safeJsonValue(asked.permissions);
|
|
2086
|
+
const metadata = {
|
|
2087
|
+
threadId: asked.threadId,
|
|
2088
|
+
turnId: asked.turnId,
|
|
2089
|
+
cwd: asked.cwd,
|
|
2090
|
+
permissions,
|
|
2091
|
+
startedAtMs: asked.startedAtMs
|
|
2092
|
+
};
|
|
2093
|
+
if (typeof asked.reason === "string")
|
|
2094
|
+
metadata.reason = asked.reason;
|
|
2095
|
+
if (typeof asked.environmentId === "string")
|
|
2096
|
+
metadata.environmentId = asked.environmentId;
|
|
2097
|
+
const detail = {
|
|
2098
|
+
method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
|
|
2099
|
+
permissions
|
|
2100
|
+
};
|
|
2101
|
+
return {
|
|
2102
|
+
detail,
|
|
2103
|
+
deltaFields: {
|
|
2104
|
+
...callId !== undefined && { callId },
|
|
2105
|
+
...typeof asked.reason === "string" && { prompt: asked.reason },
|
|
2106
|
+
input: safeJsonValue(metadata)
|
|
2107
|
+
}
|
|
2108
|
+
};
|
|
2109
|
+
}
|
|
2110
|
+
function parseCodexElicitationRequest(params) {
|
|
2111
|
+
const asked = CodexMcpElicitationParamsSchema.parse(params);
|
|
2112
|
+
const toolName = nonEmptyString(asked.serverName);
|
|
2113
|
+
const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
|
|
2114
|
+
const metadata = {
|
|
2115
|
+
serverName: asked.serverName,
|
|
2116
|
+
threadId: asked.threadId,
|
|
2117
|
+
mode: asked.mode,
|
|
2118
|
+
message: asked.message
|
|
2119
|
+
};
|
|
2120
|
+
if (asked.turnId !== undefined)
|
|
2121
|
+
metadata.turnId = asked.turnId;
|
|
2122
|
+
if (asked.environmentId !== undefined)
|
|
2123
|
+
metadata.environmentId = asked.environmentId;
|
|
2124
|
+
if (asked._meta !== undefined)
|
|
2125
|
+
metadata._meta = asked._meta;
|
|
2126
|
+
if (asked.mode === "url") {
|
|
2127
|
+
metadata.elicitationId = asked.elicitationId;
|
|
2128
|
+
metadata.url = asked.url;
|
|
2129
|
+
} else {
|
|
2130
|
+
metadata.requestedSchema = asked.requestedSchema;
|
|
2131
|
+
}
|
|
2132
|
+
const detail = {
|
|
2133
|
+
method: CODEX_ELICITATION_REQUEST,
|
|
2134
|
+
elicitationMode: asked.mode
|
|
2135
|
+
};
|
|
2136
|
+
return {
|
|
2137
|
+
detail,
|
|
2138
|
+
deltaFields: {
|
|
2139
|
+
...callId !== undefined && { callId },
|
|
2140
|
+
...toolName !== undefined && { toolName },
|
|
2141
|
+
prompt: asked.message,
|
|
2142
|
+
input: safeJsonValue(metadata)
|
|
2143
|
+
}
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
function parseCodexServerRequest(method, params) {
|
|
2147
|
+
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
2148
|
+
return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
|
|
2149
|
+
}
|
|
2150
|
+
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
2151
|
+
return { kind: "approval", ...parseCodexPermissionsRequest(params) };
|
|
2152
|
+
}
|
|
2153
|
+
if (method === CODEX_ELICITATION_REQUEST) {
|
|
2154
|
+
return { kind: "input", ...parseCodexElicitationRequest(params) };
|
|
2155
|
+
}
|
|
2156
|
+
return { kind: "input", ...parseCodexInputRequest(params) };
|
|
2157
|
+
}
|
|
2158
|
+
function codexStoppedAnswer(method) {
|
|
2159
|
+
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
2160
|
+
return { decision: CODEX_APPROVAL_DECISION.interrupted };
|
|
2161
|
+
}
|
|
2162
|
+
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
2163
|
+
return { permissions: {} };
|
|
2164
|
+
}
|
|
2165
|
+
if (method === CODEX_ELICITATION_REQUEST) {
|
|
2166
|
+
return { action: "cancel" };
|
|
2167
|
+
}
|
|
2168
|
+
return { answers: {} };
|
|
2169
|
+
}
|
|
2170
|
+
var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
|
|
2171
|
+
function buildCodexRequestAnswer(detail, rawReply) {
|
|
2172
|
+
const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
|
|
2173
|
+
if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
|
|
2174
|
+
if (reply.kind === "input") {
|
|
2175
|
+
throw new TypeError("A Codex approval is approved or denied, not answered with input");
|
|
2176
|
+
}
|
|
2177
|
+
if (reply.kind === "approve" && reply.updatedInput !== undefined) {
|
|
2178
|
+
throw new TypeError("Codex approval requests do not support updatedInput");
|
|
2179
|
+
}
|
|
2180
|
+
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;
|
|
2181
|
+
if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
|
|
2182
|
+
throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
|
|
2183
|
+
}
|
|
2184
|
+
if (detail.availableDecisions !== undefined) {
|
|
2185
|
+
const allowed = detail.availableDecisions.some((entry) => entry === decision);
|
|
2186
|
+
if (!allowed) {
|
|
2187
|
+
throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
return { decision };
|
|
2191
|
+
}
|
|
2192
|
+
if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
2193
|
+
if (reply.kind === "input") {
|
|
2194
|
+
throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
|
|
2195
|
+
}
|
|
2196
|
+
if (reply.kind === "approve") {
|
|
2197
|
+
if (reply.updatedInput !== undefined) {
|
|
2198
|
+
throw new TypeError("Codex permissions approval requests do not support updatedInput");
|
|
2199
|
+
}
|
|
2200
|
+
return {
|
|
2201
|
+
permissions: detail.permissions ?? {},
|
|
2202
|
+
scope: reply.scope === "session" ? "session" : "turn"
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
if (reply.interrupt === true) {
|
|
2206
|
+
throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
|
|
2207
|
+
}
|
|
2208
|
+
return { permissions: {} };
|
|
2209
|
+
}
|
|
2210
|
+
if (detail.method === CODEX_ELICITATION_REQUEST) {
|
|
2211
|
+
if (reply.kind === "approve") {
|
|
2212
|
+
throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
|
|
2213
|
+
}
|
|
2214
|
+
if (reply.kind === "deny") {
|
|
2215
|
+
return {
|
|
2216
|
+
action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
|
|
2217
|
+
};
|
|
2218
|
+
}
|
|
2219
|
+
const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
|
|
2220
|
+
return {
|
|
2221
|
+
action: parsed.action,
|
|
2222
|
+
...parsed.content !== undefined && { content: parsed.content },
|
|
2223
|
+
...parsed._meta !== undefined && { _meta: parsed._meta }
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
if (reply.kind !== "input") {
|
|
2227
|
+
throw new TypeError("A Codex input request is answered with input");
|
|
2228
|
+
}
|
|
2229
|
+
return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
|
|
2230
|
+
}
|
|
2231
|
+
function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
|
|
2232
|
+
const waiting = turn.pending.get(interactionId);
|
|
2233
|
+
if (waiting === undefined) {
|
|
2234
|
+
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
2235
|
+
}
|
|
2236
|
+
const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
|
|
2237
|
+
answerEngineRequest(turn, interactionId, answer);
|
|
2238
|
+
}
|
|
2239
|
+
function answerCodexSessionRequest(input) {
|
|
2240
|
+
if (input.turn?.pending.has(input.interactionId)) {
|
|
2241
|
+
answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
|
|
2242
|
+
return;
|
|
2243
|
+
}
|
|
2244
|
+
const external = input.externalPending.get(input.interactionId);
|
|
2245
|
+
if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
|
|
2246
|
+
throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
|
|
2247
|
+
}
|
|
2248
|
+
const answer = buildCodexRequestAnswer(external.detail, input.reply);
|
|
2249
|
+
input.externalPending.delete(input.interactionId);
|
|
2250
|
+
external.resolve(answer);
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
// src/agent-executor/codex/thread-open.ts
|
|
2254
|
+
function interruptLocalCodexTurn(turn, turnId) {
|
|
2255
|
+
if (turn === undefined || turn.codexTurnId !== turnId)
|
|
2256
|
+
return;
|
|
2257
|
+
turn.state.interruptRequested = true;
|
|
2258
|
+
drainEngineRequests(turn, codexStopped);
|
|
2259
|
+
}
|
|
2260
|
+
function buildCodexResumeThreadParams(params) {
|
|
2261
|
+
const caller = "CodexControlClient.resumeThread";
|
|
2262
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2263
|
+
assertOptionalNonEmptyNoNulString(params.cwd, "cwd", caller);
|
|
2264
|
+
if (params.excludeTurns !== undefined && typeof params.excludeTurns !== "boolean") {
|
|
2265
|
+
throw new TypeError(`[stitchkit] ${caller}: excludeTurns must be a boolean`);
|
|
2266
|
+
}
|
|
2267
|
+
const policyParams = buildCodexThreadPolicyParams({}, params);
|
|
2268
|
+
return {
|
|
2269
|
+
threadId,
|
|
2270
|
+
excludeTurns: params.excludeTurns ?? true,
|
|
2271
|
+
...policyParams,
|
|
2272
|
+
...params.cwd !== undefined && { cwd: params.cwd }
|
|
2273
|
+
};
|
|
2274
|
+
}
|
|
2275
|
+
function createCodexStartTurn(input) {
|
|
2276
|
+
return guardedTurnStarter({
|
|
2277
|
+
busyMessage: "A turn is already running in this Codex thread",
|
|
2278
|
+
check: (turnInput) => {
|
|
2279
|
+
input.ensureAlive();
|
|
2280
|
+
if (input.getTurn() !== undefined) {
|
|
2281
|
+
throw new Error("A turn is already running in this Codex thread");
|
|
2282
|
+
}
|
|
2283
|
+
validateCodexTurnStartOverrides("CodexSession.startTurn", turnInput, input.activeModelProvider);
|
|
2284
|
+
},
|
|
2285
|
+
inline: (turnInput) => inlineCodexParts(turnInput.input, {
|
|
2286
|
+
...input.config,
|
|
2287
|
+
driverLabel: "The Codex driver",
|
|
2288
|
+
signal: input.signal
|
|
2289
|
+
}),
|
|
2290
|
+
dispatch: async (turnInput, parts) => {
|
|
2291
|
+
const turnParams = buildCodexTurnStartRpcParams("CodexSession.startTurn", input.threadId, turnInput, parts, input.activeModelProvider);
|
|
2292
|
+
const starting = new CodexStartingTurn;
|
|
2293
|
+
const turn = {
|
|
2294
|
+
threadId: input.threadId,
|
|
2295
|
+
starting,
|
|
2296
|
+
state: { turnId: turnInput.turnId, interruptRequested: false },
|
|
2297
|
+
channel: createTurnDeltaChannel(),
|
|
2298
|
+
pending: new Map
|
|
2299
|
+
};
|
|
2300
|
+
input.setTurn(turn);
|
|
2301
|
+
let nativeTurnId;
|
|
2302
|
+
try {
|
|
2303
|
+
const started = await input.peer.request("turn/start", turnParams);
|
|
2304
|
+
nativeTurnId = parseCodexResponse("turn/start", CodexStartedTurnSchema, started).turn.id;
|
|
2305
|
+
turn.codexTurnId = nativeTurnId;
|
|
2306
|
+
delete turn.starting;
|
|
2307
|
+
starting.flush();
|
|
2308
|
+
} catch (error) {
|
|
2309
|
+
if (input.getTurn() === turn)
|
|
2310
|
+
input.setTurn(undefined);
|
|
2311
|
+
if (turn.starting !== undefined) {
|
|
2312
|
+
delete turn.starting;
|
|
2313
|
+
starting.flush();
|
|
2314
|
+
}
|
|
2315
|
+
throw error;
|
|
2316
|
+
}
|
|
2317
|
+
return {
|
|
2318
|
+
nativeTurnId,
|
|
2319
|
+
deltas: turn.channel,
|
|
2320
|
+
async interrupt() {
|
|
2321
|
+
interruptLocalCodexTurn(turn, nativeTurnId);
|
|
2322
|
+
await input.peer.request("turn/interrupt", {
|
|
2323
|
+
threadId: input.threadId,
|
|
2324
|
+
turnId: nativeTurnId
|
|
2325
|
+
});
|
|
2326
|
+
},
|
|
2327
|
+
async respond(interactionId, rawReply) {
|
|
2328
|
+
answerActiveCodexTurnRequest(turn, interactionId, rawReply);
|
|
2329
|
+
}
|
|
2330
|
+
};
|
|
2331
|
+
}
|
|
2332
|
+
});
|
|
2013
2333
|
}
|
|
2014
|
-
function
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
...question.options !== undefined && {
|
|
2022
|
-
options: question.options === null ? null : question.options.map((option) => ({
|
|
2023
|
-
label: option.label,
|
|
2024
|
-
description: option.description
|
|
2025
|
-
}))
|
|
2026
|
-
},
|
|
2027
|
-
...question.isOther !== undefined && { isOther: question.isOther },
|
|
2028
|
-
...question.isSecret !== undefined && { isSecret: question.isSecret }
|
|
2029
|
-
}));
|
|
2030
|
-
const detail = { method: CODEX_INPUT_REQUEST };
|
|
2031
|
-
return {
|
|
2032
|
-
detail,
|
|
2033
|
-
deltaFields: {
|
|
2034
|
-
...callId !== undefined && { callId },
|
|
2035
|
-
input: safeJsonValue(questions)
|
|
2334
|
+
function validateCodexOpenInput(input) {
|
|
2335
|
+
if (input.nativeThreadId !== undefined && input.forkFrom !== undefined) {
|
|
2336
|
+
throw new TypeError("[stitchkit] CodexDriver.open: nativeThreadId and forkFrom are mutually exclusive");
|
|
2337
|
+
}
|
|
2338
|
+
if (input.forkFrom !== undefined) {
|
|
2339
|
+
if (typeof input.forkFrom.threadId !== "string" || input.forkFrom.threadId.trim().length === 0) {
|
|
2340
|
+
throw new TypeError("[stitchkit] CodexDriver.open: forkFrom.threadId must be a non-empty string");
|
|
2036
2341
|
}
|
|
2037
|
-
|
|
2342
|
+
validateCodexForkBounds(input.forkFrom, "CodexDriver.open");
|
|
2343
|
+
validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
|
|
2344
|
+
}
|
|
2038
2345
|
}
|
|
2039
|
-
function
|
|
2040
|
-
const
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
if (typeof asked.environmentId === "string")
|
|
2053
|
-
metadata.environmentId = asked.environmentId;
|
|
2054
|
-
const detail = {
|
|
2055
|
-
method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
|
|
2056
|
-
permissions
|
|
2346
|
+
function mergeOpenThreadPolicy(config, forkFrom, dynamicOverrides) {
|
|
2347
|
+
const basePolicy = {
|
|
2348
|
+
...config.model !== undefined && { model: config.model },
|
|
2349
|
+
...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
|
|
2350
|
+
...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
|
|
2351
|
+
...config.sandbox !== undefined && { sandbox: config.sandbox },
|
|
2352
|
+
...config.developerInstructions !== undefined && {
|
|
2353
|
+
developerInstructions: config.developerInstructions
|
|
2354
|
+
},
|
|
2355
|
+
...config.runtimeWorkspaceRoots !== undefined && {
|
|
2356
|
+
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
2357
|
+
},
|
|
2358
|
+
...config.config !== undefined && { config: config.config }
|
|
2057
2359
|
};
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2360
|
+
const withFork = forkFrom === undefined ? basePolicy : {
|
|
2361
|
+
...basePolicy,
|
|
2362
|
+
...forkFrom.model !== undefined && { model: forkFrom.model },
|
|
2363
|
+
...forkFrom.modelProvider !== undefined && {
|
|
2364
|
+
modelProvider: forkFrom.modelProvider
|
|
2365
|
+
},
|
|
2366
|
+
...forkFrom.approvalPolicy !== undefined && {
|
|
2367
|
+
approvalPolicy: forkFrom.approvalPolicy
|
|
2368
|
+
},
|
|
2369
|
+
...forkFrom.sandbox !== undefined && { sandbox: forkFrom.sandbox },
|
|
2370
|
+
...forkFrom.developerInstructions !== undefined && {
|
|
2371
|
+
developerInstructions: forkFrom.developerInstructions
|
|
2372
|
+
},
|
|
2373
|
+
...forkFrom.runtimeWorkspaceRoots !== undefined && {
|
|
2374
|
+
runtimeWorkspaceRoots: forkFrom.runtimeWorkspaceRoots
|
|
2375
|
+
},
|
|
2376
|
+
...basePolicy.config !== undefined || forkFrom.config !== undefined ? { config: { ...basePolicy.config ?? {}, ...forkFrom.config ?? {} } } : {}
|
|
2065
2377
|
};
|
|
2378
|
+
return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
|
|
2066
2379
|
}
|
|
2067
|
-
function
|
|
2068
|
-
const
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
const metadata = {
|
|
2072
|
-
serverName: asked.serverName,
|
|
2073
|
-
threadId: asked.threadId,
|
|
2074
|
-
mode: asked.mode,
|
|
2075
|
-
message: asked.message
|
|
2380
|
+
function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
|
|
2381
|
+
const threadParams = {
|
|
2382
|
+
cwd: input.cwd,
|
|
2383
|
+
...mergeOpenThreadPolicy(config, input.forkFrom, dynamicOverrides)
|
|
2076
2384
|
};
|
|
2077
|
-
if (
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2385
|
+
if (input.forkFrom !== undefined) {
|
|
2386
|
+
const fork = input.forkFrom;
|
|
2387
|
+
return peer.request("thread/fork", {
|
|
2388
|
+
threadId: fork.threadId,
|
|
2389
|
+
excludeTurns: fork.excludeTurns ?? true,
|
|
2390
|
+
...threadParams,
|
|
2391
|
+
...fork.beforeTurnId !== undefined && { beforeTurnId: fork.beforeTurnId },
|
|
2392
|
+
...fork.lastTurnId !== undefined && { lastTurnId: fork.lastTurnId },
|
|
2393
|
+
...fork.deferGoalContinuation !== undefined && {
|
|
2394
|
+
deferGoalContinuation: fork.deferGoalContinuation
|
|
2395
|
+
}
|
|
2396
|
+
});
|
|
2088
2397
|
}
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2398
|
+
if (input.nativeThreadId !== undefined) {
|
|
2399
|
+
return peer.request("thread/resume", {
|
|
2400
|
+
threadId: input.nativeThreadId,
|
|
2401
|
+
excludeTurns: true,
|
|
2402
|
+
...threadParams
|
|
2403
|
+
});
|
|
2404
|
+
}
|
|
2405
|
+
return peer.request("thread/start", threadParams);
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
// src/agent-executor/codex/control-client.ts
|
|
2409
|
+
function createCodexControlClient(input) {
|
|
2410
|
+
const call = async (method, params, rpcOptions) => {
|
|
2411
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
2412
|
+
input.ensureAlive();
|
|
2413
|
+
return input.peer.request(method, params, rpcOptions);
|
|
2092
2414
|
};
|
|
2093
2415
|
return {
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2416
|
+
...createCodexReadMethods(call),
|
|
2417
|
+
async resumeThread(params, rpcOptions) {
|
|
2418
|
+
input.ensureAlive();
|
|
2419
|
+
return parseCodexResponse("thread/resume", CodexResumeThreadResponseSchema, await call("thread/resume", buildCodexResumeThreadParams(params), rpcOptions));
|
|
2420
|
+
},
|
|
2421
|
+
async startThreadTurn(params, rpcOptions) {
|
|
2422
|
+
input.ensureAlive();
|
|
2423
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
2424
|
+
const caller = "CodexControlClient.startThreadTurn";
|
|
2425
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2426
|
+
validateCodexTurnStartOverrides(caller, params);
|
|
2427
|
+
const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(params.input, {
|
|
2428
|
+
...input.imageOptions,
|
|
2429
|
+
driverLabel: "The Codex driver",
|
|
2430
|
+
signal
|
|
2431
|
+
}));
|
|
2432
|
+
input.ensureAlive();
|
|
2433
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
2434
|
+
const rpcParams = buildCodexTurnStartRpcParams(caller, threadId, params, parts);
|
|
2435
|
+
const started = parseCodexResponse("turn/start", CodexStartedTurnSchema, await call("turn/start", rpcParams, rpcOptions));
|
|
2436
|
+
return { turnId: started.turn.id };
|
|
2437
|
+
},
|
|
2438
|
+
async steerTurn(params, rpcOptions) {
|
|
2439
|
+
input.ensureAlive();
|
|
2440
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
2441
|
+
const caller = "CodexControlClient.steerTurn";
|
|
2442
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2443
|
+
const expectedTurnId = assertRequiredNonEmptyString(params.expectedTurnId, "expectedTurnId", caller);
|
|
2444
|
+
assertOptionalNonEmptyString(params.clientId, "clientId", caller);
|
|
2445
|
+
const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(params.input, {
|
|
2446
|
+
...input.imageOptions,
|
|
2447
|
+
driverLabel: "The Codex driver",
|
|
2448
|
+
signal
|
|
2449
|
+
}));
|
|
2450
|
+
input.ensureAlive();
|
|
2451
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
2452
|
+
return sendCodexTurnSteer(input.peer, {
|
|
2453
|
+
threadId,
|
|
2454
|
+
expectedTurnId,
|
|
2455
|
+
parts,
|
|
2456
|
+
...params.clientId !== undefined && { clientId: params.clientId }
|
|
2457
|
+
}, rpcOptions);
|
|
2458
|
+
},
|
|
2459
|
+
...createCodexThreadControlMethods(call, {
|
|
2460
|
+
ensureAlive: input.ensureAlive,
|
|
2461
|
+
...input.onBeforeInterruptTurn !== undefined && {
|
|
2462
|
+
onBeforeInterruptTurn: input.onBeforeInterruptTurn
|
|
2463
|
+
}
|
|
2464
|
+
})
|
|
2101
2465
|
};
|
|
2102
2466
|
}
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2467
|
+
|
|
2468
|
+
// src/agent-executor/codex/limits.ts
|
|
2469
|
+
import { z as z4 } from "zod";
|
|
2470
|
+
var MAX_WINDOW_NAME_CHARS = 256;
|
|
2471
|
+
var MAX_PLAN_WINDOWS = 32;
|
|
2472
|
+
var EPOCH_MS_THRESHOLD = 1000000000000;
|
|
2473
|
+
var WindowSchema = z4.looseObject({
|
|
2474
|
+
usedPercent: z4.number().min(0).optional(),
|
|
2475
|
+
used_percent: z4.number().min(0).optional(),
|
|
2476
|
+
windowDurationMins: z4.number().positive().nullable().optional(),
|
|
2477
|
+
window_duration_mins: z4.number().positive().nullable().optional(),
|
|
2478
|
+
window_minutes: z4.number().positive().nullable().optional(),
|
|
2479
|
+
resetsAt: z4.union([z4.number(), z4.string()]).nullable().optional(),
|
|
2480
|
+
resets_at: z4.union([z4.number(), z4.string()]).nullable().optional()
|
|
2481
|
+
});
|
|
2482
|
+
var SnapshotSchema = z4.looseObject({
|
|
2483
|
+
limitId: z4.string().nullable().optional(),
|
|
2484
|
+
limit_id: z4.string().nullable().optional(),
|
|
2485
|
+
limitName: z4.string().nullable().optional(),
|
|
2486
|
+
limit_name: z4.string().nullable().optional(),
|
|
2487
|
+
planType: z4.string().nullable().optional(),
|
|
2488
|
+
plan_type: z4.string().nullable().optional(),
|
|
2489
|
+
primary: z4.unknown().optional(),
|
|
2490
|
+
secondary: z4.unknown().optional()
|
|
2491
|
+
});
|
|
2492
|
+
function positiveSafeInt(value) {
|
|
2493
|
+
return isPositiveSafeInteger(value) ? value : undefined;
|
|
2114
2494
|
}
|
|
2115
|
-
function
|
|
2116
|
-
if (
|
|
2117
|
-
return
|
|
2495
|
+
function parseCodexResetsAt(raw) {
|
|
2496
|
+
if (raw === undefined || raw === null)
|
|
2497
|
+
return;
|
|
2498
|
+
if (typeof raw === "number") {
|
|
2499
|
+
if (!Number.isFinite(raw) || raw <= 0)
|
|
2500
|
+
return;
|
|
2501
|
+
return raw < EPOCH_MS_THRESHOLD ? epochSecondsToIso(raw) : epochMsToIso(raw);
|
|
2118
2502
|
}
|
|
2119
|
-
|
|
2120
|
-
|
|
2503
|
+
const trimmed = raw.trim();
|
|
2504
|
+
if (trimmed.length === 0)
|
|
2505
|
+
return;
|
|
2506
|
+
const parsed = PlanWindowSchema2.shape.resetsAt.safeParse(trimmed);
|
|
2507
|
+
return parsed.success ? parsed.data : undefined;
|
|
2508
|
+
}
|
|
2509
|
+
function resolveWindowFields(raw) {
|
|
2510
|
+
const parsed = WindowSchema.safeParse(raw);
|
|
2511
|
+
if (!parsed.success)
|
|
2512
|
+
return;
|
|
2513
|
+
const window = parsed.data;
|
|
2514
|
+
const usedPercent = window.usedPercent ?? window.used_percent;
|
|
2515
|
+
if (usedPercent === undefined || !Number.isFinite(usedPercent) || usedPercent < 0) {
|
|
2516
|
+
return;
|
|
2121
2517
|
}
|
|
2122
|
-
|
|
2123
|
-
|
|
2518
|
+
const mins = positiveSafeInt(window.windowDurationMins ?? window.window_duration_mins ?? window.window_minutes);
|
|
2519
|
+
const resetsAt = parseCodexResetsAt(window.resetsAt ?? window.resets_at);
|
|
2520
|
+
return { usedPercent, mins, resetsAt };
|
|
2521
|
+
}
|
|
2522
|
+
function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
|
|
2523
|
+
const label = clampPlanName(snapshot.limitName ?? snapshot.limit_name, MAX_WINDOW_NAME_CHARS);
|
|
2524
|
+
const primary = resolveWindowFields(snapshot.primary);
|
|
2525
|
+
const secondary = resolveWindowFields(snapshot.secondary);
|
|
2526
|
+
const duplicateDuration = primary !== undefined && secondary !== undefined && primary.mins !== undefined && primary.mins === secondary.mins;
|
|
2527
|
+
const slots = [
|
|
2528
|
+
["primary", primary],
|
|
2529
|
+
["secondary", secondary]
|
|
2530
|
+
];
|
|
2531
|
+
for (const [slot, window] of slots) {
|
|
2532
|
+
if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
|
|
2533
|
+
continue;
|
|
2534
|
+
const suffix = window.mins === undefined ? `:${slot}` : duplicateDuration ? `:${window.mins}m:${slot}` : `:${window.mins}m`;
|
|
2535
|
+
const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
|
|
2536
|
+
out.push(PlanWindowSchema2.parse({
|
|
2537
|
+
name,
|
|
2538
|
+
usedPercent: Math.min(100, window.usedPercent),
|
|
2539
|
+
...window.resetsAt !== undefined && { resetsAt: window.resetsAt },
|
|
2540
|
+
...window.mins !== undefined && { windowDurationMins: window.mins },
|
|
2541
|
+
...label !== undefined && { label }
|
|
2542
|
+
}));
|
|
2124
2543
|
}
|
|
2125
|
-
return { answers: {} };
|
|
2126
2544
|
}
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
const
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
if (reply.kind === "approve" && reply.updatedInput !== undefined) {
|
|
2135
|
-
throw new TypeError("Codex approval requests do not support updatedInput");
|
|
2545
|
+
function parseCodexRateLimitsInternal(reported) {
|
|
2546
|
+
const windows = [];
|
|
2547
|
+
const seenNames = new Set;
|
|
2548
|
+
let plan;
|
|
2549
|
+
const capturePlan = (snapshot) => {
|
|
2550
|
+
if (plan === undefined) {
|
|
2551
|
+
plan = clampPlanName(snapshot.planType ?? snapshot.plan_type, MAX_WINDOW_NAME_CHARS);
|
|
2136
2552
|
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2553
|
+
};
|
|
2554
|
+
if (isRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported) || ("rate_limits" in reported) || ("rate_limits_by_limit_id" in reported))) {
|
|
2555
|
+
const seenLimitIds = new Set;
|
|
2556
|
+
const rawById = reported.rateLimitsByLimitId ?? reported.rate_limits_by_limit_id;
|
|
2557
|
+
if (isRecord(rawById)) {
|
|
2558
|
+
for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
|
|
2559
|
+
const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
|
|
2560
|
+
if (!parsed.success)
|
|
2561
|
+
continue;
|
|
2562
|
+
capturePlan(parsed.data);
|
|
2563
|
+
const limitId = nonEmptyString(parsed.data.limitId ?? parsed.data.limit_id)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
|
|
2564
|
+
seenLimitIds.add(limitId);
|
|
2565
|
+
appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
|
|
2566
|
+
if (windows.length >= MAX_PLAN_WINDOWS)
|
|
2567
|
+
return { windows, plan };
|
|
2568
|
+
}
|
|
2140
2569
|
}
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2570
|
+
const rawSingle = reported.rateLimits ?? reported.rate_limits;
|
|
2571
|
+
if (windows.length < MAX_PLAN_WINDOWS && rawSingle !== undefined) {
|
|
2572
|
+
const parsedSingle = SnapshotSchema.safeParse(rawSingle);
|
|
2573
|
+
if (parsedSingle.success) {
|
|
2574
|
+
capturePlan(parsedSingle.data);
|
|
2575
|
+
const explicitId = nonEmptyString(parsedSingle.data.limitId ?? parsedSingle.data.limit_id)?.trim();
|
|
2576
|
+
const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
|
|
2577
|
+
if (shouldIncludeSingle) {
|
|
2578
|
+
appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
|
|
2579
|
+
}
|
|
2145
2580
|
}
|
|
2146
2581
|
}
|
|
2147
|
-
return {
|
|
2148
|
-
}
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2582
|
+
return { windows, plan };
|
|
2583
|
+
}
|
|
2584
|
+
const single = SnapshotSchema.safeParse(reported);
|
|
2585
|
+
if (!single.success)
|
|
2586
|
+
return { windows: [], plan: undefined };
|
|
2587
|
+
capturePlan(single.data);
|
|
2588
|
+
const limitId = nonEmptyString(single.data.limitId ?? single.data.limit_id)?.trim() ?? "limit";
|
|
2589
|
+
appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
|
|
2590
|
+
return { windows, plan };
|
|
2591
|
+
}
|
|
2592
|
+
function codexPlanWindows(reported) {
|
|
2593
|
+
return parseCodexRateLimitsInternal(reported).windows;
|
|
2594
|
+
}
|
|
2595
|
+
function codexPlanLimits(reported, now = new Date) {
|
|
2596
|
+
const { windows, plan } = parseCodexRateLimitsInternal(reported);
|
|
2597
|
+
return PlanLimitsSchema2.parse({
|
|
2598
|
+
answer: windows.length > 0 ? "known" : "unpublished",
|
|
2599
|
+
windows,
|
|
2600
|
+
observedAt: now.toISOString(),
|
|
2601
|
+
...plan !== undefined && { plan }
|
|
2602
|
+
});
|
|
2603
|
+
}
|
|
2604
|
+
|
|
2605
|
+
// src/agent-executor/codex/pagination.ts
|
|
2606
|
+
var DEFAULT_FIND_TURN_MAX_PAGES = 256;
|
|
2607
|
+
var DEFAULT_FIND_TURN_PAGE_SIZE = 50;
|
|
2608
|
+
var MAX_UINT322 = 4294967295;
|
|
2609
|
+
async function walkCodexPages(fetchPage, options, onPage, repeatedCursorLabel) {
|
|
2610
|
+
assertPositiveSafeInteger("maxPages", options.maxPages, TypeError, { absent: "refused" });
|
|
2611
|
+
const onRepeatedCursor = options.onRepeatedCursor ?? "throw";
|
|
2612
|
+
if (onRepeatedCursor !== "throw" && onRepeatedCursor !== "stop") {
|
|
2613
|
+
throw new TypeError(`[stitchkit] iterateCodexPages: onRepeatedCursor must be "throw" or "stop", received ${JSON.stringify(onRepeatedCursor)}`);
|
|
2614
|
+
}
|
|
2615
|
+
const signal = options.signal;
|
|
2616
|
+
const seen = new Set;
|
|
2617
|
+
let cursor;
|
|
2618
|
+
for (let pageIndex = 0;pageIndex < options.maxPages; pageIndex += 1) {
|
|
2619
|
+
if (signal?.aborted)
|
|
2620
|
+
throw abortReason(signal);
|
|
2621
|
+
const pending = fetchPage(cursor);
|
|
2622
|
+
const page = signal !== undefined ? await raceAbort(pending, signal) : await pending;
|
|
2623
|
+
if (signal?.aborted)
|
|
2624
|
+
throw abortReason(signal);
|
|
2625
|
+
if (onPage(page) === "stop") {
|
|
2626
|
+
return { truncated: false, stoppedByConsumer: true };
|
|
2627
|
+
}
|
|
2628
|
+
const next = page.nextCursor;
|
|
2629
|
+
if (next === null || next === undefined) {
|
|
2630
|
+
return { truncated: false, stoppedByConsumer: false };
|
|
2152
2631
|
}
|
|
2153
|
-
if (
|
|
2154
|
-
if (
|
|
2155
|
-
|
|
2632
|
+
if (seen.has(next)) {
|
|
2633
|
+
if (onRepeatedCursor === "stop") {
|
|
2634
|
+
return { truncated: true, stoppedByConsumer: false };
|
|
2156
2635
|
}
|
|
2157
|
-
|
|
2158
|
-
permissions: detail.permissions ?? {},
|
|
2159
|
-
scope: reply.scope === "session" ? "session" : "turn"
|
|
2160
|
-
};
|
|
2161
|
-
}
|
|
2162
|
-
if (reply.interrupt === true) {
|
|
2163
|
-
throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
|
|
2636
|
+
throw new Error(`Codex ${repeatedCursorLabel} repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
2164
2637
|
}
|
|
2165
|
-
|
|
2638
|
+
seen.add(next);
|
|
2639
|
+
cursor = next;
|
|
2166
2640
|
}
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2641
|
+
return { truncated: true, stoppedByConsumer: false };
|
|
2642
|
+
}
|
|
2643
|
+
async function iterateCodexPages(fetchPage, options) {
|
|
2644
|
+
const pages = [];
|
|
2645
|
+
const outcome = await walkCodexPages(fetchPage, options, (page) => {
|
|
2646
|
+
pages.push(page);
|
|
2647
|
+
return "continue";
|
|
2648
|
+
}, "pagination");
|
|
2649
|
+
return { pages, truncated: outcome.truncated };
|
|
2650
|
+
}
|
|
2651
|
+
async function findCodexTurnByClientId(controls, params) {
|
|
2652
|
+
const caller = "findCodexTurnByClientId";
|
|
2653
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2654
|
+
const clientId = assertRequiredNonEmptyString(params.clientId, "clientId", caller);
|
|
2655
|
+
const maxPages = params.maxPages ?? DEFAULT_FIND_TURN_MAX_PAGES;
|
|
2656
|
+
const pageSize = params.pageSize ?? DEFAULT_FIND_TURN_PAGE_SIZE;
|
|
2657
|
+
assertPositiveSafeInteger(`[stitchkit] ${caller}: maxPages`, maxPages);
|
|
2658
|
+
assertPositiveSafeInteger(`[stitchkit] ${caller}: pageSize`, pageSize);
|
|
2659
|
+
if (pageSize > MAX_UINT322) {
|
|
2660
|
+
throw new TypeError(`[stitchkit] ${caller}: pageSize must not exceed ${MAX_UINT322}`);
|
|
2661
|
+
}
|
|
2662
|
+
if (params.timeoutMs !== undefined) {
|
|
2663
|
+
assertTimerMs("timeoutMs", params.timeoutMs);
|
|
2664
|
+
}
|
|
2665
|
+
const rpcOptions = params.timeoutMs !== undefined || params.signal !== undefined ? {
|
|
2666
|
+
...params.timeoutMs !== undefined && { timeoutMs: params.timeoutMs },
|
|
2667
|
+
...params.signal !== undefined && { signal: params.signal }
|
|
2668
|
+
} : undefined;
|
|
2669
|
+
let matched = null;
|
|
2670
|
+
const outcome = await walkCodexPages((cursor) => controls.listTurns({
|
|
2671
|
+
threadId,
|
|
2672
|
+
limit: pageSize,
|
|
2673
|
+
itemsView: "full",
|
|
2674
|
+
...cursor !== undefined && { cursor }
|
|
2675
|
+
}, rpcOptions), {
|
|
2676
|
+
maxPages,
|
|
2677
|
+
signal: params.signal,
|
|
2678
|
+
onRepeatedCursor: "throw"
|
|
2679
|
+
}, (page) => {
|
|
2680
|
+
for (const turn of page.data) {
|
|
2681
|
+
if (turn.itemsView !== undefined && turn.itemsView !== "full") {
|
|
2682
|
+
throw new Error(`Codex thread/turns/list returned incomplete itemsView ${JSON.stringify(turn.itemsView)} for turn ${turn.id}`);
|
|
2683
|
+
}
|
|
2170
2684
|
}
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2685
|
+
for (const turn of page.data) {
|
|
2686
|
+
if (turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId)) {
|
|
2687
|
+
matched = turn;
|
|
2688
|
+
return "stop";
|
|
2689
|
+
}
|
|
2175
2690
|
}
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
};
|
|
2182
|
-
}
|
|
2183
|
-
if (reply.kind !== "input") {
|
|
2184
|
-
throw new TypeError("A Codex input request is answered with input");
|
|
2185
|
-
}
|
|
2186
|
-
return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
|
|
2187
|
-
}
|
|
2188
|
-
function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
|
|
2189
|
-
const waiting = turn.pending.get(interactionId);
|
|
2190
|
-
if (waiting === undefined) {
|
|
2191
|
-
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
2192
|
-
}
|
|
2193
|
-
const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
|
|
2194
|
-
answerEngineRequest(turn, interactionId, answer);
|
|
2195
|
-
}
|
|
2196
|
-
function answerCodexSessionRequest(input) {
|
|
2197
|
-
if (input.turn?.pending.has(input.interactionId)) {
|
|
2198
|
-
answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
|
|
2199
|
-
return;
|
|
2200
|
-
}
|
|
2201
|
-
const external = input.externalPending.get(input.interactionId);
|
|
2202
|
-
if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
|
|
2203
|
-
throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
|
|
2691
|
+
return "continue";
|
|
2692
|
+
}, "thread/turns/list");
|
|
2693
|
+
if (outcome.stoppedByConsumer)
|
|
2694
|
+
return matched;
|
|
2695
|
+
if (outcome.truncated) {
|
|
2696
|
+
throw new Error(`Codex thread/turns/list exceeded ${maxPages} pages without reaching the end of history`);
|
|
2204
2697
|
}
|
|
2205
|
-
|
|
2206
|
-
input.externalPending.delete(input.interactionId);
|
|
2207
|
-
external.resolve(answer);
|
|
2698
|
+
return null;
|
|
2208
2699
|
}
|
|
2209
2700
|
|
|
2210
2701
|
// src/agent-executor/codex/handlers.ts
|
|
@@ -2216,9 +2707,9 @@ function emitCodexNotification(state, method, params, duringActiveTurn, deltas)
|
|
|
2216
2707
|
invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
|
|
2217
2708
|
}
|
|
2218
2709
|
function handleCodexNotification(state, method, params) {
|
|
2219
|
-
const turn = state.getTurn();
|
|
2710
|
+
const turn = codexEventTurn(state.getTurn(), params);
|
|
2220
2711
|
const duringActiveTurn = turn !== undefined;
|
|
2221
|
-
const effectiveTurnId = turn?.state.turnId ??
|
|
2712
|
+
const effectiveTurnId = turn?.state.turnId ?? codexTurnIdOf(params) ?? "external";
|
|
2222
2713
|
let verdict;
|
|
2223
2714
|
try {
|
|
2224
2715
|
verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: effectiveTurnId, interruptRequested: false });
|
|
@@ -2239,9 +2730,11 @@ function handleCodexNotification(state, method, params) {
|
|
|
2239
2730
|
switch (verdict.kind) {
|
|
2240
2731
|
case "limits":
|
|
2241
2732
|
try {
|
|
2733
|
+
const parsedLimits = codexPlanLimits(verdict.rateLimits, new Date);
|
|
2242
2734
|
state.limits.set(state.profileId, mergeRateLimitEvent2({
|
|
2243
2735
|
previous: state.limits.get(state.profileId),
|
|
2244
|
-
windows:
|
|
2736
|
+
windows: parsedLimits.windows,
|
|
2737
|
+
...parsedLimits.plan !== undefined && { plan: parsedLimits.plan },
|
|
2245
2738
|
now: new Date
|
|
2246
2739
|
}));
|
|
2247
2740
|
emitCodexNotification(state, method, params, duringActiveTurn, []);
|
|
@@ -2262,7 +2755,9 @@ function handleCodexNotification(state, method, params) {
|
|
|
2262
2755
|
case "resolved": {
|
|
2263
2756
|
const resolvedTurn = turn?.pending.delete(verdict.requestId) === true;
|
|
2264
2757
|
const externalEntry = state.externalPending.get(verdict.requestId);
|
|
2265
|
-
const
|
|
2758
|
+
const threadId = codexThreadIdOf(params);
|
|
2759
|
+
const nativeTurnId = codexTurnIdOf(params);
|
|
2760
|
+
const resolvedExternal = !resolvedTurn && externalEntry !== undefined && (threadId === undefined || externalEntry.threadId === undefined || threadId === externalEntry.threadId) && (nativeTurnId === undefined || nativeTurnId === externalEntry.turnId);
|
|
2266
2761
|
if (resolvedExternal)
|
|
2267
2762
|
state.externalPending.delete(verdict.requestId);
|
|
2268
2763
|
const resolvedDelta = {
|
|
@@ -2274,7 +2769,7 @@ function handleCodexNotification(state, method, params) {
|
|
|
2274
2769
|
};
|
|
2275
2770
|
if (resolvedTurn && turn !== undefined)
|
|
2276
2771
|
offerTurnDelta(turn.channel, resolvedDelta);
|
|
2277
|
-
emitCodexNotification(state, method, params, duringActiveTurn, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
|
|
2772
|
+
emitCodexNotification(state, method, params, duringActiveTurn && !resolvedExternal, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
|
|
2278
2773
|
return;
|
|
2279
2774
|
}
|
|
2280
2775
|
case "deltas":
|
|
@@ -2289,7 +2784,8 @@ function handleCodexNotification(state, method, params) {
|
|
|
2289
2784
|
}
|
|
2290
2785
|
case "end":
|
|
2291
2786
|
endEngineTurn(turn, codexStopped, verdict.deltas);
|
|
2292
|
-
|
|
2787
|
+
if (turn !== undefined)
|
|
2788
|
+
state.clearTurn();
|
|
2293
2789
|
emitCodexNotification(state, method, params, duringActiveTurn, verdict.deltas);
|
|
2294
2790
|
return;
|
|
2295
2791
|
case "ignore":
|
|
@@ -2298,7 +2794,7 @@ function handleCodexNotification(state, method, params) {
|
|
|
2298
2794
|
}
|
|
2299
2795
|
}
|
|
2300
2796
|
function handleCodexRequest(state, method, params, id) {
|
|
2301
|
-
const turn = state.getTurn();
|
|
2797
|
+
const turn = codexEventTurn(state.getTurn(), params);
|
|
2302
2798
|
if (!isKnownCodexRequestMethod(method)) {
|
|
2303
2799
|
if (turn !== undefined) {
|
|
2304
2800
|
offerTurnDelta(turn.channel, {
|
|
@@ -2315,24 +2811,40 @@ function handleCodexRequest(state, method, params, id) {
|
|
|
2315
2811
|
const interactionId = String(id);
|
|
2316
2812
|
if (turn !== undefined) {
|
|
2317
2813
|
const parsed = parseCodexServerRequest(method, params);
|
|
2318
|
-
|
|
2814
|
+
const delta = {
|
|
2815
|
+
type: "request",
|
|
2816
|
+
turnId: turn.state.turnId,
|
|
2817
|
+
itemId: `request:${interactionId}`,
|
|
2818
|
+
raw: { source: "codex", type: method },
|
|
2819
|
+
interactionId,
|
|
2820
|
+
kind: parsed.kind,
|
|
2821
|
+
...parsed.deltaFields
|
|
2822
|
+
};
|
|
2823
|
+
const promise = new Promise((resolve) => {
|
|
2319
2824
|
holdEngineRequest(turn, {
|
|
2320
2825
|
interactionId,
|
|
2321
2826
|
detail: parsed.detail,
|
|
2322
2827
|
answeredBy: { source: "codex", type: method },
|
|
2323
|
-
delta: () =>
|
|
2324
|
-
type: "request",
|
|
2325
|
-
turnId: turn.state.turnId,
|
|
2326
|
-
itemId: `request:${interactionId}`,
|
|
2327
|
-
raw: { source: "codex", type: method },
|
|
2328
|
-
interactionId,
|
|
2329
|
-
kind: parsed.kind,
|
|
2330
|
-
...parsed.deltaFields
|
|
2331
|
-
}),
|
|
2828
|
+
delta: () => delta,
|
|
2332
2829
|
refusal: codexStoppedAnswer(method),
|
|
2333
2830
|
resolve
|
|
2334
2831
|
});
|
|
2335
2832
|
});
|
|
2833
|
+
if (state.serverRequestDelivery === "all" && state.onServerRequest !== undefined && turn.pending.has(interactionId)) {
|
|
2834
|
+
const observer = state.onServerRequest;
|
|
2835
|
+
invokeSafely(() => observer({
|
|
2836
|
+
interactionId,
|
|
2837
|
+
requestId: id,
|
|
2838
|
+
method,
|
|
2839
|
+
params,
|
|
2840
|
+
duringActiveTurn: true,
|
|
2841
|
+
delta,
|
|
2842
|
+
async respond(reply) {
|
|
2843
|
+
answerActiveCodexTurnRequest(turn, interactionId, reply);
|
|
2844
|
+
}
|
|
2845
|
+
}));
|
|
2846
|
+
}
|
|
2847
|
+
return promise;
|
|
2336
2848
|
}
|
|
2337
2849
|
const observer = state.onServerRequest;
|
|
2338
2850
|
if (observer === undefined) {
|
|
@@ -2345,7 +2857,7 @@ function handleCodexRequest(state, method, params, id) {
|
|
|
2345
2857
|
throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
|
|
2346
2858
|
}
|
|
2347
2859
|
const parsed = parseCodexServerRequest(method, params);
|
|
2348
|
-
const turnId =
|
|
2860
|
+
const turnId = codexTurnIdOf(params) ?? "external";
|
|
2349
2861
|
const delta = {
|
|
2350
2862
|
type: "request",
|
|
2351
2863
|
turnId,
|
|
@@ -2356,7 +2868,13 @@ function handleCodexRequest(state, method, params, id) {
|
|
|
2356
2868
|
...parsed.deltaFields
|
|
2357
2869
|
};
|
|
2358
2870
|
return new Promise((resolve, reject) => {
|
|
2359
|
-
const
|
|
2871
|
+
const threadId = codexThreadIdOf(params);
|
|
2872
|
+
const entry = {
|
|
2873
|
+
detail: parsed.detail,
|
|
2874
|
+
turnId,
|
|
2875
|
+
...threadId !== undefined && { threadId },
|
|
2876
|
+
resolve
|
|
2877
|
+
};
|
|
2360
2878
|
state.externalPending.set(interactionId, entry);
|
|
2361
2879
|
const onObserverError = (error) => {
|
|
2362
2880
|
if (state.externalPending.get(interactionId) !== entry)
|
|
@@ -2367,363 +2885,146 @@ function handleCodexRequest(state, method, params, id) {
|
|
|
2367
2885
|
};
|
|
2368
2886
|
try {
|
|
2369
2887
|
const outcome = observer({
|
|
2370
|
-
interactionId,
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
|
|
2385
|
-
Promise.resolve(outcome).catch(onObserverError);
|
|
2386
|
-
}
|
|
2387
|
-
} catch (error) {
|
|
2388
|
-
onObserverError(error);
|
|
2389
|
-
}
|
|
2390
|
-
});
|
|
2391
|
-
}
|
|
2392
|
-
function createCodexHandlers(state) {
|
|
2393
|
-
return {
|
|
2394
|
-
onNotification: (method, params) => handleCodexNotification(state, method, params),
|
|
2395
|
-
onRequest: (method, params, id) => handleCodexRequest(state, method, params, id)
|
|
2396
|
-
};
|
|
2397
|
-
}
|
|
2398
|
-
|
|
2399
|
-
// src/agent-executor/codex/turn-input.ts
|
|
2400
|
-
import { z as z3 } from "zod";
|
|
2401
|
-
var NonEmptyNoNulStringSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00"), {
|
|
2402
|
-
message: "must be a non-empty string without NUL bytes"
|
|
2403
|
-
});
|
|
2404
|
-
var CodexSkillInputSchema = z3.strictObject({
|
|
2405
|
-
type: z3.literal("skill"),
|
|
2406
|
-
name: NonEmptyNoNulStringSchema,
|
|
2407
|
-
path: NonEmptyNoNulStringSchema
|
|
2408
|
-
});
|
|
2409
|
-
function validateSkillInput(part) {
|
|
2410
|
-
if (part.type !== "skill")
|
|
2411
|
-
return;
|
|
2412
|
-
const parsed = CodexSkillInputSchema.safeParse(part);
|
|
2413
|
-
if (!parsed.success) {
|
|
2414
|
-
throw new TypeError("Codex skill input name and path must be non-empty strings without NUL bytes");
|
|
2415
|
-
}
|
|
2416
|
-
return { type: "skill", name: parsed.data.name, path: parsed.data.path };
|
|
2417
|
-
}
|
|
2418
|
-
function inlineCodexParts(parts, options) {
|
|
2419
|
-
return inlineOrderedParts(parts, {
|
|
2420
|
-
...options,
|
|
2421
|
-
acceptedDescription: "text, images, and skills",
|
|
2422
|
-
validateExtra: validateSkillInput
|
|
2423
|
-
});
|
|
2424
|
-
}
|
|
2425
|
-
function codexTurnInput(parts) {
|
|
2426
|
-
if (parts.every((part) => part.type === "text")) {
|
|
2427
|
-
return [
|
|
2428
|
-
{ type: "text", text: parts.map((part) => part.text).join(`
|
|
2429
|
-
`), text_elements: [] }
|
|
2430
|
-
];
|
|
2431
|
-
}
|
|
2432
|
-
const out = [];
|
|
2433
|
-
for (const part of parts) {
|
|
2434
|
-
if (part.type === "text") {
|
|
2435
|
-
out.push({ type: "text", text: part.text, text_elements: [] });
|
|
2436
|
-
} else if (part.type === "skill") {
|
|
2437
|
-
out.push({ type: "skill", name: part.name, path: part.path });
|
|
2438
|
-
} else {
|
|
2439
|
-
out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
|
|
2440
|
-
}
|
|
2441
|
-
}
|
|
2442
|
-
return out;
|
|
2443
|
-
}
|
|
2444
|
-
|
|
2445
|
-
// src/agent-executor/codex/session-controls.ts
|
|
2446
|
-
function validateCodexForkBounds(options, caller) {
|
|
2447
|
-
if (options.beforeTurnId !== undefined && options.lastTurnId !== undefined) {
|
|
2448
|
-
throw new TypeError(`[stitchkit] ${caller}: beforeTurnId and lastTurnId are mutually exclusive`);
|
|
2449
|
-
}
|
|
2450
|
-
}
|
|
2451
|
-
function validateCodexPolicyOverrides(overrides, caller) {
|
|
2452
|
-
if (overrides.runtimeWorkspaceRoots !== undefined) {
|
|
2453
|
-
if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
|
|
2454
|
-
throw new TypeError(`[stitchkit] ${caller}: runtimeWorkspaceRoots must be an array of strings`);
|
|
2455
|
-
}
|
|
2456
|
-
for (const root of overrides.runtimeWorkspaceRoots) {
|
|
2457
|
-
if (typeof root !== "string" || root.trim().length === 0) {
|
|
2458
|
-
throw new TypeError(`[stitchkit] ${caller}: every runtimeWorkspaceRoots entry must be a non-empty string`);
|
|
2459
|
-
}
|
|
2460
|
-
}
|
|
2461
|
-
}
|
|
2462
|
-
if (overrides.config !== undefined) {
|
|
2463
|
-
if (typeof overrides.config !== "object" || overrides.config === null || Array.isArray(overrides.config)) {
|
|
2464
|
-
throw new TypeError(`[stitchkit] ${caller}: config must be a plain JSON object`);
|
|
2465
|
-
}
|
|
2466
|
-
safeJsonValue(overrides.config);
|
|
2467
|
-
}
|
|
2468
|
-
}
|
|
2469
|
-
function buildCodexThreadPolicyParams(base, overrides) {
|
|
2470
|
-
const mergedConfig = base.config !== undefined || overrides?.config !== undefined ? { ...base.config ?? {}, ...overrides?.config ?? {} } : undefined;
|
|
2471
|
-
const merged = {
|
|
2472
|
-
...base,
|
|
2473
|
-
...overrides,
|
|
2474
|
-
...mergedConfig !== undefined && { config: mergedConfig }
|
|
2475
|
-
};
|
|
2476
|
-
validateCodexPolicyOverrides(merged, "CodexSession");
|
|
2477
|
-
const params = {};
|
|
2478
|
-
if (merged.model !== undefined)
|
|
2479
|
-
params.model = merged.model;
|
|
2480
|
-
if (merged.modelProvider !== undefined)
|
|
2481
|
-
params.modelProvider = merged.modelProvider;
|
|
2482
|
-
if (merged.approvalPolicy !== undefined)
|
|
2483
|
-
params.approvalPolicy = safeJsonValue(merged.approvalPolicy);
|
|
2484
|
-
if (merged.sandbox !== undefined)
|
|
2485
|
-
params.sandbox = merged.sandbox;
|
|
2486
|
-
if (merged.developerInstructions !== undefined)
|
|
2487
|
-
params.developerInstructions = merged.developerInstructions;
|
|
2488
|
-
if (merged.runtimeWorkspaceRoots !== undefined)
|
|
2489
|
-
params.runtimeWorkspaceRoots = [...merged.runtimeWorkspaceRoots];
|
|
2490
|
-
if (merged.config !== undefined)
|
|
2491
|
-
params.config = safeJsonValue(merged.config);
|
|
2492
|
-
return params;
|
|
2493
|
-
}
|
|
2494
|
-
function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
|
|
2495
|
-
if (turnInput.modelProvider !== undefined) {
|
|
2496
|
-
if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
|
|
2497
|
-
throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
|
|
2498
|
-
}
|
|
2499
|
-
}
|
|
2500
|
-
if (turnInput.collaborationMode !== undefined) {
|
|
2501
|
-
CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
|
|
2502
|
-
}
|
|
2503
|
-
if (turnInput.approvalPolicy !== undefined) {
|
|
2504
|
-
safeJsonValue(turnInput.approvalPolicy);
|
|
2505
|
-
}
|
|
2506
|
-
if (turnInput.sandboxPolicy !== undefined) {
|
|
2507
|
-
safeJsonValue(turnInput.sandboxPolicy);
|
|
2508
|
-
}
|
|
2509
|
-
if (turnInput.runtimeWorkspaceRoots !== undefined) {
|
|
2510
|
-
validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, "CodexSession.startTurn");
|
|
2511
|
-
}
|
|
2512
|
-
}
|
|
2513
|
-
function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvider) {
|
|
2514
|
-
validateCodexTurnStartOverrides(turnInput, activeModelProvider);
|
|
2515
|
-
const params = {
|
|
2516
|
-
threadId,
|
|
2517
|
-
input: codexTurnInput(parts),
|
|
2518
|
-
clientUserMessageId: turnInput.clientId
|
|
2519
|
-
};
|
|
2520
|
-
if (turnInput.model !== undefined)
|
|
2521
|
-
params.model = turnInput.model;
|
|
2522
|
-
if (turnInput.reasoningEffort !== undefined)
|
|
2523
|
-
params.effort = turnInput.reasoningEffort;
|
|
2524
|
-
if (turnInput.collaborationMode !== undefined) {
|
|
2525
|
-
params.collaborationMode = CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
|
|
2526
|
-
}
|
|
2527
|
-
if (turnInput.approvalPolicy !== undefined) {
|
|
2528
|
-
params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
|
|
2529
|
-
}
|
|
2530
|
-
if (turnInput.sandboxPolicy !== undefined) {
|
|
2531
|
-
params.sandboxPolicy = safeJsonValue(turnInput.sandboxPolicy);
|
|
2532
|
-
}
|
|
2533
|
-
if (turnInput.runtimeWorkspaceRoots !== undefined) {
|
|
2534
|
-
params.runtimeWorkspaceRoots = [...turnInput.runtimeWorkspaceRoots];
|
|
2535
|
-
}
|
|
2536
|
-
return params;
|
|
2537
|
-
}
|
|
2538
|
-
function createCodexSessionMutators(input) {
|
|
2539
|
-
return {
|
|
2540
|
-
async steerTurn(steerInput) {
|
|
2541
|
-
input.ensureAlive();
|
|
2542
|
-
const active = input.getActiveTurn();
|
|
2543
|
-
const expectedTurnId = active?.codexTurnId;
|
|
2544
|
-
if (active === undefined || expectedTurnId === undefined) {
|
|
2545
|
-
throw new Error("Cannot steer turn: no Codex turn is currently running");
|
|
2546
|
-
}
|
|
2547
|
-
if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== expectedTurnId) {
|
|
2548
|
-
throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${expectedTurnId}`);
|
|
2549
|
-
}
|
|
2550
|
-
const parts = await inlineCodexParts(steerInput.input, {
|
|
2551
|
-
...input.imageOptions,
|
|
2552
|
-
driverLabel: "The Codex driver",
|
|
2553
|
-
signal: input.signal
|
|
2554
|
-
});
|
|
2555
|
-
input.ensureAlive();
|
|
2556
|
-
const afterAwait = input.getActiveTurn();
|
|
2557
|
-
if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
|
|
2558
|
-
throw new Error("Cannot steer turn: the active Codex turn ended before steering was sent");
|
|
2559
|
-
}
|
|
2560
|
-
const steered = CodexTurnSteerResponseSchema.parse(await input.peer.request("turn/steer", {
|
|
2561
|
-
threadId: input.threadId,
|
|
2562
|
-
expectedTurnId,
|
|
2563
|
-
input: codexTurnInput(parts),
|
|
2564
|
-
...steerInput.clientId !== undefined && {
|
|
2565
|
-
clientUserMessageId: steerInput.clientId
|
|
2566
|
-
}
|
|
2567
|
-
}));
|
|
2568
|
-
return { turnId: steered.turnId };
|
|
2569
|
-
},
|
|
2570
|
-
async forkThread(options = {}) {
|
|
2571
|
-
input.ensureAlive();
|
|
2572
|
-
validateCodexForkBounds(options, "CodexSession.forkThread");
|
|
2573
|
-
const policyParams = buildCodexThreadPolicyParams({}, options);
|
|
2574
|
-
const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
|
|
2575
|
-
threadId: input.threadId,
|
|
2576
|
-
...policyParams,
|
|
2577
|
-
...options.cwd !== undefined && { cwd: options.cwd },
|
|
2578
|
-
...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
|
|
2579
|
-
...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
|
|
2580
|
-
...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns },
|
|
2581
|
-
...options.deferGoalContinuation !== undefined && {
|
|
2582
|
-
deferGoalContinuation: options.deferGoalContinuation
|
|
2888
|
+
interactionId,
|
|
2889
|
+
requestId: id,
|
|
2890
|
+
method,
|
|
2891
|
+
params,
|
|
2892
|
+
duringActiveTurn: false,
|
|
2893
|
+
delta,
|
|
2894
|
+
async respond(reply) {
|
|
2895
|
+
answerCodexSessionRequest({
|
|
2896
|
+
turn: undefined,
|
|
2897
|
+
externalPending: state.externalPending,
|
|
2898
|
+
expectedEntry: entry,
|
|
2899
|
+
interactionId,
|
|
2900
|
+
reply
|
|
2901
|
+
});
|
|
2583
2902
|
}
|
|
2584
|
-
})
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
threadContext: extractCodexThreadContext(forked)
|
|
2588
|
-
};
|
|
2589
|
-
},
|
|
2590
|
-
async compactThread() {
|
|
2591
|
-
input.ensureAlive();
|
|
2592
|
-
await input.peer.request("thread/compact/start", { threadId: input.threadId });
|
|
2593
|
-
}
|
|
2594
|
-
};
|
|
2595
|
-
}
|
|
2596
|
-
|
|
2597
|
-
// src/agent-executor/codex/session.ts
|
|
2598
|
-
function createCodexStartTurn(input) {
|
|
2599
|
-
return guardedTurnStarter({
|
|
2600
|
-
busyMessage: "A turn is already running in this Codex thread",
|
|
2601
|
-
check: (turnInput) => {
|
|
2602
|
-
input.ensureAlive();
|
|
2603
|
-
if (input.getTurn() !== undefined) {
|
|
2604
|
-
throw new Error("A turn is already running in this Codex thread");
|
|
2605
|
-
}
|
|
2606
|
-
validateCodexTurnStartOverrides(turnInput, input.activeModelProvider);
|
|
2607
|
-
},
|
|
2608
|
-
inline: (turnInput) => inlineCodexParts(turnInput.input, {
|
|
2609
|
-
...input.config,
|
|
2610
|
-
driverLabel: "The Codex driver",
|
|
2611
|
-
signal: input.signal
|
|
2612
|
-
}),
|
|
2613
|
-
dispatch: async (turnInput, parts) => {
|
|
2614
|
-
const turnParams = buildCodexTurnStartParams(input.threadId, turnInput, parts, input.activeModelProvider);
|
|
2615
|
-
const turn = {
|
|
2616
|
-
state: { turnId: turnInput.turnId, interruptRequested: false },
|
|
2617
|
-
channel: createTurnDeltaChannel(),
|
|
2618
|
-
pending: new Map
|
|
2619
|
-
};
|
|
2620
|
-
input.setTurn(turn);
|
|
2621
|
-
try {
|
|
2622
|
-
const started = await input.peer.request("turn/start", turnParams);
|
|
2623
|
-
turn.codexTurnId = CodexStartedTurnSchema.parse(started).turn.id;
|
|
2624
|
-
} catch (error) {
|
|
2625
|
-
if (input.getTurn() === turn)
|
|
2626
|
-
input.setTurn(undefined);
|
|
2627
|
-
throw error;
|
|
2903
|
+
});
|
|
2904
|
+
if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
|
|
2905
|
+
Promise.resolve(outcome).catch(onObserverError);
|
|
2628
2906
|
}
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
async interrupt() {
|
|
2632
|
-
turn.state.interruptRequested = true;
|
|
2633
|
-
drainEngineRequests(turn, codexStopped);
|
|
2634
|
-
if (turn.codexTurnId !== undefined) {
|
|
2635
|
-
await input.peer.request("turn/interrupt", {
|
|
2636
|
-
threadId: input.threadId,
|
|
2637
|
-
turnId: turn.codexTurnId
|
|
2638
|
-
});
|
|
2639
|
-
}
|
|
2640
|
-
},
|
|
2641
|
-
async respond(interactionId, rawReply) {
|
|
2642
|
-
answerActiveCodexTurnRequest(turn, interactionId, rawReply);
|
|
2643
|
-
}
|
|
2644
|
-
};
|
|
2907
|
+
} catch (error) {
|
|
2908
|
+
onObserverError(error);
|
|
2645
2909
|
}
|
|
2646
2910
|
});
|
|
2647
2911
|
}
|
|
2648
|
-
function
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2912
|
+
function createCodexHandlers(state) {
|
|
2913
|
+
return {
|
|
2914
|
+
onNotification(method, params) {
|
|
2915
|
+
const starting = codexEventTurn(state.getTurn(), params)?.starting;
|
|
2916
|
+
const deliver = () => handleCodexNotification(state, method, params);
|
|
2917
|
+
if (starting === undefined)
|
|
2918
|
+
deliver();
|
|
2919
|
+
else
|
|
2920
|
+
starting.defer(params, deliver);
|
|
2921
|
+
},
|
|
2922
|
+
onRequest(method, params, id) {
|
|
2923
|
+
const starting = codexEventTurn(state.getTurn(), params)?.starting;
|
|
2924
|
+
const deliver = () => handleCodexRequest(state, method, params, id);
|
|
2925
|
+
if (starting === undefined)
|
|
2926
|
+
return deliver();
|
|
2927
|
+
return new Promise((resolve, reject) => {
|
|
2928
|
+
starting.defer(params, () => {
|
|
2929
|
+
try {
|
|
2930
|
+
resolve(deliver());
|
|
2931
|
+
} catch (error) {
|
|
2932
|
+
reject(error);
|
|
2933
|
+
}
|
|
2934
|
+
});
|
|
2935
|
+
});
|
|
2655
2936
|
}
|
|
2656
|
-
|
|
2657
|
-
validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
|
|
2658
|
-
}
|
|
2937
|
+
};
|
|
2659
2938
|
}
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2939
|
+
|
|
2940
|
+
// src/agent-executor/codex/session-bind.ts
|
|
2941
|
+
function bindCodexSessionThreadControls(controlClient, threadId) {
|
|
2942
|
+
return {
|
|
2943
|
+
readThread(params, options) {
|
|
2944
|
+
return controlClient.readThread({
|
|
2945
|
+
...params,
|
|
2946
|
+
threadId: params?.threadId ?? threadId
|
|
2947
|
+
}, options);
|
|
2668
2948
|
},
|
|
2669
|
-
|
|
2670
|
-
|
|
2949
|
+
listTurns(params, options) {
|
|
2950
|
+
return controlClient.listTurns({
|
|
2951
|
+
...params,
|
|
2952
|
+
threadId: params?.threadId ?? threadId
|
|
2953
|
+
}, options);
|
|
2671
2954
|
},
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
...forkFrom.modelProvider !== undefined && {
|
|
2678
|
-
modelProvider: forkFrom.modelProvider
|
|
2955
|
+
listItems(params, options) {
|
|
2956
|
+
return controlClient.listItems({
|
|
2957
|
+
...params,
|
|
2958
|
+
threadId: params?.threadId ?? threadId
|
|
2959
|
+
}, options);
|
|
2679
2960
|
},
|
|
2680
|
-
|
|
2681
|
-
|
|
2961
|
+
resumeThread(params, options) {
|
|
2962
|
+
return controlClient.resumeThread({
|
|
2963
|
+
...params,
|
|
2964
|
+
threadId: params?.threadId ?? threadId
|
|
2965
|
+
}, options);
|
|
2682
2966
|
},
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2967
|
+
revertThread(params, options) {
|
|
2968
|
+
return controlClient.revertThread({
|
|
2969
|
+
...params,
|
|
2970
|
+
threadId: params.threadId ?? threadId
|
|
2971
|
+
}, options);
|
|
2686
2972
|
},
|
|
2687
|
-
|
|
2688
|
-
|
|
2973
|
+
injectItems(params, options) {
|
|
2974
|
+
return controlClient.injectItems({
|
|
2975
|
+
...params,
|
|
2976
|
+
threadId: params.threadId ?? threadId
|
|
2977
|
+
}, options);
|
|
2689
2978
|
},
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
}
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2979
|
+
unsubscribeThread(params, options) {
|
|
2980
|
+
return controlClient.unsubscribeThread({
|
|
2981
|
+
threadId: params?.threadId ?? threadId
|
|
2982
|
+
}, options);
|
|
2983
|
+
},
|
|
2984
|
+
archiveThread(params, options) {
|
|
2985
|
+
return controlClient.archiveThread({
|
|
2986
|
+
threadId: params?.threadId ?? threadId
|
|
2987
|
+
}, options);
|
|
2988
|
+
},
|
|
2989
|
+
unarchiveThread(params, options) {
|
|
2990
|
+
return controlClient.unarchiveThread({
|
|
2991
|
+
threadId: params?.threadId ?? threadId
|
|
2992
|
+
}, options);
|
|
2993
|
+
},
|
|
2994
|
+
updateThreadMetadata(params, options) {
|
|
2995
|
+
return controlClient.updateThreadMetadata({
|
|
2996
|
+
...params,
|
|
2997
|
+
threadId: params?.threadId ?? threadId
|
|
2998
|
+
}, options);
|
|
2999
|
+
},
|
|
3000
|
+
setThreadName(params, options) {
|
|
3001
|
+
return controlClient.setThreadName({
|
|
3002
|
+
...params,
|
|
3003
|
+
threadId: params.threadId ?? threadId
|
|
3004
|
+
}, options);
|
|
3005
|
+
},
|
|
3006
|
+
interruptTurn(params, options) {
|
|
3007
|
+
return controlClient.interruptTurn({
|
|
3008
|
+
...params,
|
|
3009
|
+
threadId: params.threadId ?? threadId
|
|
3010
|
+
}, options);
|
|
3011
|
+
},
|
|
3012
|
+
compactThread(params, options) {
|
|
3013
|
+
return controlClient.compactThread({
|
|
3014
|
+
threadId: params?.threadId ?? threadId
|
|
3015
|
+
}, options);
|
|
3016
|
+
}
|
|
2698
3017
|
};
|
|
2699
|
-
if (input.forkFrom !== undefined) {
|
|
2700
|
-
const fork = input.forkFrom;
|
|
2701
|
-
return peer.request("thread/fork", {
|
|
2702
|
-
threadId: fork.threadId,
|
|
2703
|
-
excludeTurns: fork.excludeTurns ?? true,
|
|
2704
|
-
...threadParams,
|
|
2705
|
-
...fork.beforeTurnId !== undefined && { beforeTurnId: fork.beforeTurnId },
|
|
2706
|
-
...fork.lastTurnId !== undefined && { lastTurnId: fork.lastTurnId },
|
|
2707
|
-
...fork.deferGoalContinuation !== undefined && {
|
|
2708
|
-
deferGoalContinuation: fork.deferGoalContinuation
|
|
2709
|
-
}
|
|
2710
|
-
});
|
|
2711
|
-
}
|
|
2712
|
-
if (input.nativeThreadId !== undefined) {
|
|
2713
|
-
return peer.request("thread/resume", {
|
|
2714
|
-
threadId: input.nativeThreadId,
|
|
2715
|
-
excludeTurns: true,
|
|
2716
|
-
...threadParams
|
|
2717
|
-
});
|
|
2718
|
-
}
|
|
2719
|
-
return peer.request("thread/start", threadParams);
|
|
2720
3018
|
}
|
|
3019
|
+
|
|
3020
|
+
// src/agent-executor/codex/session.ts
|
|
2721
3021
|
async function openCodexSession(config, input) {
|
|
2722
3022
|
validateCodexOpenInput(input);
|
|
2723
3023
|
const profile = engineProfile("codex", input.profile);
|
|
2724
3024
|
const linked = sessionAbort(input.signal);
|
|
2725
3025
|
const externalPending = new Map;
|
|
2726
3026
|
let current;
|
|
3027
|
+
let activeThreadId;
|
|
2727
3028
|
let dead;
|
|
2728
3029
|
let opened = false;
|
|
2729
3030
|
let closing = false;
|
|
@@ -2740,6 +3041,9 @@ async function openCodexSession(config, input) {
|
|
|
2740
3041
|
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
2741
3042
|
...config.onServerRequest !== undefined && {
|
|
2742
3043
|
onServerRequest: config.onServerRequest
|
|
3044
|
+
},
|
|
3045
|
+
...config.serverRequestDelivery !== undefined && {
|
|
3046
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
2743
3047
|
}
|
|
2744
3048
|
}), (error) => {
|
|
2745
3049
|
const shouldNotify = opened && !closing && input.signal?.aborted !== true;
|
|
@@ -2756,7 +3060,7 @@ async function openCodexSession(config, input) {
|
|
|
2756
3060
|
linked.release();
|
|
2757
3061
|
throw error;
|
|
2758
3062
|
}
|
|
2759
|
-
const { peer, providerPid } = connected;
|
|
3063
|
+
const { peer, providerPid, userAgent } = connected;
|
|
2760
3064
|
const ensureAlive = () => {
|
|
2761
3065
|
if (closing)
|
|
2762
3066
|
throw new Error("The Codex session is closed");
|
|
@@ -2773,7 +3077,16 @@ async function openCodexSession(config, input) {
|
|
|
2773
3077
|
linked.release();
|
|
2774
3078
|
}
|
|
2775
3079
|
};
|
|
2776
|
-
const controlClient = createCodexControlClient({
|
|
3080
|
+
const controlClient = createCodexControlClient({
|
|
3081
|
+
peer,
|
|
3082
|
+
imageOptions: config,
|
|
3083
|
+
signal: linked.signal,
|
|
3084
|
+
ensureAlive,
|
|
3085
|
+
onBeforeInterruptTurn: (targetThreadId, turnId) => {
|
|
3086
|
+
if (targetThreadId === activeThreadId)
|
|
3087
|
+
interruptLocalCodexTurn(current, turnId);
|
|
3088
|
+
}
|
|
3089
|
+
});
|
|
2777
3090
|
let threadId;
|
|
2778
3091
|
let threadContext;
|
|
2779
3092
|
let dynamicOverrides;
|
|
@@ -2790,8 +3103,10 @@ async function openCodexSession(config, input) {
|
|
|
2790
3103
|
linked.signal.throwIfAborted();
|
|
2791
3104
|
}
|
|
2792
3105
|
const openedReply = await openCodexThreadRpc(peer, config, input, dynamicOverrides);
|
|
2793
|
-
const
|
|
3106
|
+
const openMethod = input.forkFrom !== undefined ? "thread/fork" : input.nativeThreadId !== undefined ? "thread/resume" : "thread/start";
|
|
3107
|
+
const parsed = parseCodexResponse(openMethod, CodexStartedThreadSchema, openedReply);
|
|
2794
3108
|
threadId = parsed.thread.id;
|
|
3109
|
+
activeThreadId = threadId;
|
|
2795
3110
|
threadContext = extractCodexThreadContext(parsed);
|
|
2796
3111
|
if (config.verifyThread !== undefined) {
|
|
2797
3112
|
emitStartupPhase(input.onStartupPhase, "verifying");
|
|
@@ -2834,6 +3149,7 @@ async function openCodexSession(config, input) {
|
|
|
2834
3149
|
return {
|
|
2835
3150
|
nativeThreadId: threadId,
|
|
2836
3151
|
providerPid,
|
|
3152
|
+
userAgent,
|
|
2837
3153
|
threadContext,
|
|
2838
3154
|
startTurn,
|
|
2839
3155
|
async respond(interactionId, reply) {
|
|
@@ -2870,6 +3186,9 @@ async function openCodexControlConnection(config, input) {
|
|
|
2870
3186
|
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
2871
3187
|
...config.onServerRequest !== undefined && {
|
|
2872
3188
|
onServerRequest: config.onServerRequest
|
|
3189
|
+
},
|
|
3190
|
+
...config.serverRequestDelivery !== undefined && {
|
|
3191
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
2873
3192
|
}
|
|
2874
3193
|
}), (error) => {
|
|
2875
3194
|
const shouldNotify = opened && !closing && input.signal?.aborted !== true;
|
|
@@ -2901,10 +3220,16 @@ async function openCodexControlConnection(config, input) {
|
|
|
2901
3220
|
if (dead !== undefined)
|
|
2902
3221
|
throw dead;
|
|
2903
3222
|
};
|
|
2904
|
-
const controlClient = createCodexControlClient({
|
|
3223
|
+
const controlClient = createCodexControlClient({
|
|
3224
|
+
peer: connected.peer,
|
|
3225
|
+
imageOptions: config,
|
|
3226
|
+
signal: linked.signal,
|
|
3227
|
+
ensureAlive
|
|
3228
|
+
});
|
|
2905
3229
|
opened = true;
|
|
2906
3230
|
return {
|
|
2907
3231
|
providerPid: connected.providerPid,
|
|
3232
|
+
userAgent: connected.userAgent,
|
|
2908
3233
|
...controlClient,
|
|
2909
3234
|
async respond(interactionId, reply) {
|
|
2910
3235
|
ensureAlive();
|
|
@@ -2947,7 +3272,10 @@ function buildSharedThreadSession(params) {
|
|
|
2947
3272
|
};
|
|
2948
3273
|
const threadControlClient = createCodexControlClient({
|
|
2949
3274
|
peer: state.peer,
|
|
2950
|
-
|
|
3275
|
+
imageOptions: state.config,
|
|
3276
|
+
signal: threadAbort.signal,
|
|
3277
|
+
ensureAlive: ensureThreadAlive,
|
|
3278
|
+
onBeforeInterruptTurn: state.onBeforeInterruptTurn
|
|
2951
3279
|
});
|
|
2952
3280
|
const startTurn = createCodexStartTurn({
|
|
2953
3281
|
config: state.config,
|
|
@@ -3002,6 +3330,7 @@ function buildSharedThreadSession(params) {
|
|
|
3002
3330
|
return {
|
|
3003
3331
|
nativeThreadId: threadId,
|
|
3004
3332
|
providerPid: state.providerPid,
|
|
3333
|
+
userAgent: state.userAgent,
|
|
3005
3334
|
threadContext,
|
|
3006
3335
|
startTurn,
|
|
3007
3336
|
async respond(interactionId, reply) {
|
|
@@ -3044,12 +3373,22 @@ async function openSharedCodexThread(state, threadInput) {
|
|
|
3044
3373
|
state.openingNativeThreadIds.add(threadInput.nativeThreadId);
|
|
3045
3374
|
}
|
|
3046
3375
|
let registeredThreadId;
|
|
3376
|
+
const openControls = createCodexControlClient({
|
|
3377
|
+
peer: state.peer,
|
|
3378
|
+
imageOptions: state.config,
|
|
3379
|
+
signal: threadAbort.signal,
|
|
3380
|
+
ensureAlive: () => {
|
|
3381
|
+
threadAbort.signal.throwIfAborted();
|
|
3382
|
+
state.ensureServerAlive();
|
|
3383
|
+
},
|
|
3384
|
+
onBeforeInterruptTurn: state.onBeforeInterruptTurn
|
|
3385
|
+
});
|
|
3047
3386
|
try {
|
|
3048
3387
|
threadAbort.signal.throwIfAborted();
|
|
3049
3388
|
let dynamicOverrides;
|
|
3050
3389
|
if (state.config.prepareThread !== undefined) {
|
|
3051
3390
|
dynamicOverrides = await raceAbort(Promise.resolve(state.config.prepareThread({
|
|
3052
|
-
controls:
|
|
3391
|
+
controls: openControls,
|
|
3053
3392
|
cwd: threadInput.cwd,
|
|
3054
3393
|
...threadInput.nativeThreadId !== undefined && {
|
|
3055
3394
|
nativeThreadId: threadInput.nativeThreadId
|
|
@@ -3068,7 +3407,8 @@ async function openSharedCodexThread(state, threadInput) {
|
|
|
3068
3407
|
const openedReply = await raceAbort(openCodexThreadRpc(state.peer, state.config, threadInput, dynamicOverrides), threadAbort.signal, disposeLateOpen);
|
|
3069
3408
|
threadAbort.signal.throwIfAborted();
|
|
3070
3409
|
state.ensureServerAlive();
|
|
3071
|
-
const
|
|
3410
|
+
const openMethod = threadInput.forkFrom !== undefined ? "thread/fork" : threadInput.nativeThreadId !== undefined ? "thread/resume" : "thread/start";
|
|
3411
|
+
const parsed = parseCodexResponse(openMethod, CodexStartedThreadSchema, openedReply);
|
|
3072
3412
|
const threadId = parsed.thread.id;
|
|
3073
3413
|
const threadContext = extractCodexThreadContext(parsed);
|
|
3074
3414
|
if (state.threads.has(threadId)) {
|
|
@@ -3096,6 +3436,9 @@ async function openSharedCodexThread(state, threadInput) {
|
|
|
3096
3436
|
},
|
|
3097
3437
|
...state.config.onServerRequest !== undefined && {
|
|
3098
3438
|
onServerRequest: state.config.onServerRequest
|
|
3439
|
+
},
|
|
3440
|
+
...state.config.serverRequestDelivery !== undefined && {
|
|
3441
|
+
serverRequestDelivery: state.config.serverRequestDelivery
|
|
3099
3442
|
}
|
|
3100
3443
|
})
|
|
3101
3444
|
};
|
|
@@ -3106,7 +3449,7 @@ async function openSharedCodexThread(state, threadInput) {
|
|
|
3106
3449
|
await raceAbort(Promise.resolve(state.config.verifyThread({
|
|
3107
3450
|
nativeThreadId: threadId,
|
|
3108
3451
|
threadContext,
|
|
3109
|
-
controls:
|
|
3452
|
+
controls: openControls
|
|
3110
3453
|
})), threadAbort.signal);
|
|
3111
3454
|
threadAbort.signal.throwIfAborted();
|
|
3112
3455
|
}
|
|
@@ -3141,19 +3484,6 @@ async function openSharedCodexThread(state, threadInput) {
|
|
|
3141
3484
|
// src/agent-executor/codex/shared-server.ts
|
|
3142
3485
|
var DEFAULT_MAX_SHARED_THREADS = 32;
|
|
3143
3486
|
var HARD_MAX_SHARED_THREADS = 256;
|
|
3144
|
-
function extractCodexThreadId(params) {
|
|
3145
|
-
if (!isRecord(params))
|
|
3146
|
-
return;
|
|
3147
|
-
if (typeof params.threadId === "string" && params.threadId.length > 0)
|
|
3148
|
-
return params.threadId;
|
|
3149
|
-
if (isRecord(params.thread) && typeof params.thread.id === "string" && params.thread.id.length > 0) {
|
|
3150
|
-
return params.thread.id;
|
|
3151
|
-
}
|
|
3152
|
-
if (isRecord(params.turn) && typeof params.turn.threadId === "string" && params.turn.threadId.length > 0) {
|
|
3153
|
-
return params.turn.threadId;
|
|
3154
|
-
}
|
|
3155
|
-
return;
|
|
3156
|
-
}
|
|
3157
3487
|
function validateSharedServerInputs(config, input) {
|
|
3158
3488
|
if (config.transport !== undefined && config.transport.kind !== "stdio") {
|
|
3159
3489
|
throw new TypeError(`[stitchkit] CodexDriver.openSharedServer: shared multi-thread mode requires stdio transport (received ${JSON.stringify(config.transport.kind)})`);
|
|
@@ -3185,7 +3515,10 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3185
3515
|
return;
|
|
3186
3516
|
},
|
|
3187
3517
|
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3188
|
-
...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest }
|
|
3518
|
+
...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
|
|
3519
|
+
...config.serverRequestDelivery !== undefined && {
|
|
3520
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
3521
|
+
}
|
|
3189
3522
|
});
|
|
3190
3523
|
const failAllThreads = (error) => {
|
|
3191
3524
|
for (const slot of [...threads.values()]) {
|
|
@@ -3208,7 +3541,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3208
3541
|
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3209
3542
|
return;
|
|
3210
3543
|
}
|
|
3211
|
-
const targetId =
|
|
3544
|
+
const targetId = codexThreadIdOf(params);
|
|
3212
3545
|
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3213
3546
|
if (slot !== undefined) {
|
|
3214
3547
|
invokeSafely(() => slot.handlers.onNotification(method, params));
|
|
@@ -3217,7 +3550,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3217
3550
|
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3218
3551
|
},
|
|
3219
3552
|
onRequest(method, params, id) {
|
|
3220
|
-
const targetId =
|
|
3553
|
+
const targetId = codexThreadIdOf(params);
|
|
3221
3554
|
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3222
3555
|
if (slot !== undefined)
|
|
3223
3556
|
return slot.handlers.onRequest(method, params, id);
|
|
@@ -3236,14 +3569,23 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3236
3569
|
linked.release();
|
|
3237
3570
|
throw error;
|
|
3238
3571
|
}
|
|
3239
|
-
const { peer, providerPid } = connected;
|
|
3572
|
+
const { peer, providerPid, userAgent } = connected;
|
|
3240
3573
|
const ensureServerAlive = () => {
|
|
3241
3574
|
if (serverClosing)
|
|
3242
3575
|
throw new Error("The Codex shared server is closed");
|
|
3243
3576
|
if (serverDead !== undefined)
|
|
3244
3577
|
throw serverDead;
|
|
3245
3578
|
};
|
|
3246
|
-
const
|
|
3579
|
+
const onBeforeInterruptTurn = (targetThreadId, turnId) => {
|
|
3580
|
+
interruptLocalCodexTurn(threads.get(targetThreadId)?.current, turnId);
|
|
3581
|
+
};
|
|
3582
|
+
const controlClient = createCodexControlClient({
|
|
3583
|
+
peer,
|
|
3584
|
+
imageOptions: config,
|
|
3585
|
+
signal: linked.signal,
|
|
3586
|
+
ensureAlive: ensureServerAlive,
|
|
3587
|
+
onBeforeInterruptTurn
|
|
3588
|
+
});
|
|
3247
3589
|
const sharedCapabilities = {
|
|
3248
3590
|
...baseCapabilities,
|
|
3249
3591
|
multiThreadPerProcess: true
|
|
@@ -3253,8 +3595,9 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3253
3595
|
profile,
|
|
3254
3596
|
peer,
|
|
3255
3597
|
providerPid,
|
|
3598
|
+
userAgent,
|
|
3256
3599
|
maxThreads,
|
|
3257
|
-
|
|
3600
|
+
onBeforeInterruptTurn,
|
|
3258
3601
|
serverSignal: linked.signal,
|
|
3259
3602
|
threads,
|
|
3260
3603
|
openingNativeThreadIds: new Set,
|
|
@@ -3279,6 +3622,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3279
3622
|
opened = true;
|
|
3280
3623
|
return {
|
|
3281
3624
|
providerPid,
|
|
3625
|
+
userAgent,
|
|
3282
3626
|
maxThreads,
|
|
3283
3627
|
get activeThreadCount() {
|
|
3284
3628
|
return threads.size;
|
|
@@ -3291,36 +3635,57 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3291
3635
|
}
|
|
3292
3636
|
|
|
3293
3637
|
// src/agent-executor/codex/driver.ts
|
|
3294
|
-
var MAX_HISTORY_PAGES = 256;
|
|
3295
3638
|
var FIND_INPUT_MAX_LINE_BYTES = 64 * 1024 * 1024;
|
|
3296
|
-
|
|
3297
|
-
const seen = new Set;
|
|
3298
|
-
let cursor;
|
|
3299
|
-
for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
|
|
3300
|
-
const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
|
|
3301
|
-
threadId: nativeThreadId,
|
|
3302
|
-
limit: 50,
|
|
3303
|
-
itemsView: "full",
|
|
3304
|
-
...cursor !== undefined && { cursor }
|
|
3305
|
-
}));
|
|
3306
|
-
if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId))) {
|
|
3307
|
-
return true;
|
|
3308
|
-
}
|
|
3309
|
-
const next = page.nextCursor;
|
|
3310
|
-
if (next === null || next === undefined)
|
|
3311
|
-
return false;
|
|
3312
|
-
if (seen.has(next)) {
|
|
3313
|
-
throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
3314
|
-
}
|
|
3315
|
-
seen.add(next);
|
|
3316
|
-
cursor = next;
|
|
3317
|
-
}
|
|
3318
|
-
throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
|
|
3319
|
-
}
|
|
3320
|
-
function createCodexDriver(config = {}) {
|
|
3639
|
+
function validateCodexDriverOptions(config) {
|
|
3321
3640
|
validateImageOptions(config);
|
|
3641
|
+
assertPositiveSafeInteger("maxFrameBytes", config.maxFrameBytes);
|
|
3322
3642
|
validateCodexTransportAndArgs(config);
|
|
3323
3643
|
validateCodexPolicyOverrides(config, "createCodexDriver");
|
|
3644
|
+
if (config.serverRequestDelivery !== undefined && config.serverRequestDelivery !== "external-only" && config.serverRequestDelivery !== "all") {
|
|
3645
|
+
throw new TypeError(`[stitchkit] createCodexDriver: serverRequestDelivery must be "external-only" or "all", received ${JSON.stringify(config.serverRequestDelivery)}`);
|
|
3646
|
+
}
|
|
3647
|
+
if (config.serverRequestDelivery === "all" && config.onServerRequest === undefined) {
|
|
3648
|
+
throw new TypeError('[stitchkit] createCodexDriver: serverRequestDelivery "all" requires onServerRequest');
|
|
3649
|
+
}
|
|
3650
|
+
}
|
|
3651
|
+
function buildCodexSessionConfig(input) {
|
|
3652
|
+
const { config } = input;
|
|
3653
|
+
const transport = input.forceStdioForListen && config.transport?.kind === "unix-listen" ? { kind: "stdio" } : config.transport;
|
|
3654
|
+
const maxFrameBytes = input.maxFrameBytes ?? config.maxFrameBytes;
|
|
3655
|
+
return {
|
|
3656
|
+
executable: input.executable,
|
|
3657
|
+
prefix: input.prefix,
|
|
3658
|
+
...transport !== undefined && { transport },
|
|
3659
|
+
...config.serverArgs !== undefined && { serverArgs: config.serverArgs },
|
|
3660
|
+
...config.model !== undefined && { model: config.model },
|
|
3661
|
+
...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
|
|
3662
|
+
approvalPolicy: config.approvalPolicy ?? "on-request",
|
|
3663
|
+
sandbox: config.sandbox ?? "workspace-write",
|
|
3664
|
+
...config.developerInstructions !== undefined && {
|
|
3665
|
+
developerInstructions: config.developerInstructions
|
|
3666
|
+
},
|
|
3667
|
+
...config.runtimeWorkspaceRoots !== undefined && {
|
|
3668
|
+
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
3669
|
+
},
|
|
3670
|
+
...config.config !== undefined && { config: config.config },
|
|
3671
|
+
...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
|
|
3672
|
+
...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
|
|
3673
|
+
...!input.ephemeralProbe && config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3674
|
+
...!input.ephemeralProbe && config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
|
|
3675
|
+
...!input.ephemeralProbe && config.serverRequestDelivery !== undefined && {
|
|
3676
|
+
serverRequestDelivery: config.serverRequestDelivery
|
|
3677
|
+
},
|
|
3678
|
+
...!input.ephemeralProbe && config.onDisconnect !== undefined && { onDisconnect: config.onDisconnect },
|
|
3679
|
+
ambient: input.ambient,
|
|
3680
|
+
limits: input.limits,
|
|
3681
|
+
version: input.version,
|
|
3682
|
+
...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
|
|
3683
|
+
...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
|
|
3684
|
+
...maxFrameBytes !== undefined && { maxFrameBytes }
|
|
3685
|
+
};
|
|
3686
|
+
}
|
|
3687
|
+
function createCodexDriver(config = {}) {
|
|
3688
|
+
validateCodexDriverOptions(config);
|
|
3324
3689
|
const executable = config.executable ?? "codex";
|
|
3325
3690
|
const prefix = config.prefixArgs ?? [];
|
|
3326
3691
|
const ambient = config.ambient ?? process.env;
|
|
@@ -3342,40 +3707,18 @@ function createCodexDriver(config = {}) {
|
|
|
3342
3707
|
images: config.resolveFile !== undefined,
|
|
3343
3708
|
planLimits: "pull"
|
|
3344
3709
|
};
|
|
3345
|
-
const session = (options) => {
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
approvalPolicy: config.approvalPolicy ?? "on-request",
|
|
3355
|
-
sandbox: config.sandbox ?? "workspace-write",
|
|
3356
|
-
...config.developerInstructions !== undefined && {
|
|
3357
|
-
developerInstructions: config.developerInstructions
|
|
3358
|
-
},
|
|
3359
|
-
...config.runtimeWorkspaceRoots !== undefined && {
|
|
3360
|
-
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
3361
|
-
},
|
|
3362
|
-
...config.config !== undefined && { config: config.config },
|
|
3363
|
-
...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
|
|
3364
|
-
...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
|
|
3365
|
-
...!options?.ephemeralProbe && config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3366
|
-
...!options?.ephemeralProbe && config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
|
|
3367
|
-
...!options?.ephemeralProbe && config.onDisconnect !== undefined && { onDisconnect: config.onDisconnect },
|
|
3368
|
-
ambient,
|
|
3369
|
-
limits,
|
|
3370
|
-
version,
|
|
3371
|
-
...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
|
|
3372
|
-
...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
|
|
3373
|
-
...options?.maxLineBytes !== undefined && { maxLineBytes: options.maxLineBytes }
|
|
3374
|
-
};
|
|
3375
|
-
};
|
|
3710
|
+
const session = (options) => buildCodexSessionConfig({
|
|
3711
|
+
config,
|
|
3712
|
+
executable,
|
|
3713
|
+
prefix,
|
|
3714
|
+
ambient,
|
|
3715
|
+
limits,
|
|
3716
|
+
version,
|
|
3717
|
+
...options
|
|
3718
|
+
});
|
|
3376
3719
|
const cli = (profile, args) => runEngineCli({ executable, prefix, args, profile, ambient });
|
|
3377
|
-
const ask = (profile, cwd, question,
|
|
3378
|
-
...
|
|
3720
|
+
const ask = (profile, cwd, question, maxFrameBytes) => withEphemeralConnection((signal) => connectCodex(session({
|
|
3721
|
+
...maxFrameBytes !== undefined && { maxFrameBytes },
|
|
3379
3722
|
forceStdioForListen: true,
|
|
3380
3723
|
ephemeralProbe: true
|
|
3381
3724
|
}), engineProfile("codex", profile), cwd, signal), (connection) => question(connection.peer));
|
|
@@ -3406,37 +3749,68 @@ function createCodexDriver(config = {}) {
|
|
|
3406
3749
|
const decoder = new TextDecoder;
|
|
3407
3750
|
const text = `${decoder.decode(loginResult.stdout)}
|
|
3408
3751
|
${decoder.decode(loginResult.stderr)}`.trim();
|
|
3409
|
-
const
|
|
3410
|
-
const
|
|
3411
|
-
|
|
3752
|
+
const line = text.split(/\r?\n/).map((value) => value.trim()).find((value) => /^Logged in(?:\s|$)/i.test(value));
|
|
3753
|
+
const signedIn = loginResult.exitCode === 0 && line !== undefined;
|
|
3754
|
+
const signedOut = loginResult.exitCode === 1 && /^Not logged in\s*$/im.test(text);
|
|
3755
|
+
const credential = signedIn ? /chatgpt/i.test(line) ? "subscription" : /api key/i.test(line) ? "api-key" : "unknown" : signedOut ? "none" : "unknown";
|
|
3756
|
+
let planLimits;
|
|
3412
3757
|
if (credential === "subscription") {
|
|
3413
3758
|
try {
|
|
3414
3759
|
const answer = await ask(parsed, process.cwd(), (peer) => peer.request("account/rateLimits/read"));
|
|
3415
|
-
const
|
|
3416
|
-
planLimits =
|
|
3760
|
+
const snapshot = codexPlanLimits(answer);
|
|
3761
|
+
planLimits = {
|
|
3762
|
+
...snapshot,
|
|
3763
|
+
windows: snapshot.windows.toSorted((a, b) => a.name.localeCompare(b.name))
|
|
3764
|
+
};
|
|
3417
3765
|
limits.set(parsed.profileId, planLimits);
|
|
3418
3766
|
} catch (error) {
|
|
3419
3767
|
planLimits = planLimitsReadFailed2({
|
|
3420
|
-
previous:
|
|
3768
|
+
previous: limits.get(parsed.profileId),
|
|
3421
3769
|
error: error instanceof Error ? error.message : String(error),
|
|
3422
3770
|
now: new Date
|
|
3423
3771
|
});
|
|
3424
3772
|
}
|
|
3425
3773
|
} else if (credential === "api-key") {
|
|
3774
|
+
limits.delete(parsed.profileId);
|
|
3426
3775
|
planLimits = {
|
|
3427
3776
|
answer: "no-plan-limit",
|
|
3428
3777
|
windows: [],
|
|
3429
3778
|
observedAt: new Date().toISOString()
|
|
3430
3779
|
};
|
|
3431
3780
|
}
|
|
3781
|
+
if (signedOut)
|
|
3782
|
+
limits.delete(parsed.profileId);
|
|
3783
|
+
if (credential === "unknown") {
|
|
3784
|
+
const previous = limits.get(parsed.profileId);
|
|
3785
|
+
if (previous !== undefined)
|
|
3786
|
+
planLimits = planLimitsReadFailed2({
|
|
3787
|
+
previous,
|
|
3788
|
+
error: "Codex login status could not confirm the credential",
|
|
3789
|
+
now: new Date
|
|
3790
|
+
});
|
|
3791
|
+
}
|
|
3432
3792
|
return {
|
|
3433
|
-
login: { state: signedIn ? "signed-in" : "signed-out" },
|
|
3793
|
+
login: { state: signedIn ? "signed-in" : signedOut ? "signed-out" : "unknown" },
|
|
3434
3794
|
effectiveCredential: credential,
|
|
3435
3795
|
...planLimits && { planLimits }
|
|
3436
3796
|
};
|
|
3437
3797
|
},
|
|
3438
3798
|
async findInput(input) {
|
|
3439
|
-
return ask(input.profile, input.cwd, (peer) =>
|
|
3799
|
+
return ask(input.profile, input.cwd, async (peer) => {
|
|
3800
|
+
const controls = createCodexControlClient({
|
|
3801
|
+
peer,
|
|
3802
|
+
imageOptions: config,
|
|
3803
|
+
signal: new AbortController().signal,
|
|
3804
|
+
ensureAlive: () => {
|
|
3805
|
+
return;
|
|
3806
|
+
}
|
|
3807
|
+
});
|
|
3808
|
+
const found = await findCodexTurnByClientId(controls, {
|
|
3809
|
+
threadId: input.nativeThreadId,
|
|
3810
|
+
clientId: input.clientId
|
|
3811
|
+
});
|
|
3812
|
+
return found !== null;
|
|
3813
|
+
}, Math.max(FIND_INPUT_MAX_LINE_BYTES, config.maxFrameBytes ?? 0));
|
|
3440
3814
|
},
|
|
3441
3815
|
open: (input) => openCodexSession(session(), input),
|
|
3442
3816
|
connectControl: (input) => openCodexControlConnection(session(), input),
|
|
@@ -3529,9 +3903,55 @@ var codexFakeScenarios = {
|
|
|
3529
3903
|
crash: () => steps(text("dying "), { do: "crash" })
|
|
3530
3904
|
};
|
|
3531
3905
|
export {
|
|
3906
|
+
CODEX_THREAD_SOURCE_KINDS2 as CODEX_THREAD_SOURCE_KINDS,
|
|
3907
|
+
CODEX_TOOL_ITEMS,
|
|
3908
|
+
CodexAccountReadResponseSchema,
|
|
3909
|
+
CodexAccountSchema,
|
|
3910
|
+
CodexApprovalPolicySchema2 as CodexApprovalPolicySchema,
|
|
3911
|
+
CodexCollaborationModePresetSchema,
|
|
3912
|
+
CodexCollaborationModeSchema2 as CodexCollaborationModeSchema,
|
|
3913
|
+
CodexCollaborationModesResponseSchema,
|
|
3914
|
+
CodexConfigReadResponseSchema,
|
|
3915
|
+
CodexConfigSchema,
|
|
3916
|
+
CodexItemsPageSchema,
|
|
3917
|
+
CodexListedTurnSchema2 as CodexListedTurnSchema,
|
|
3918
|
+
CodexLoadedThreadsPageSchema,
|
|
3919
|
+
CodexLocalImageInputSchema,
|
|
3920
|
+
CodexMcpServerStatusPageSchema,
|
|
3921
|
+
CodexMcpServerStatusSchema,
|
|
3922
|
+
CodexModelSchema,
|
|
3923
|
+
CodexModelsPageSchema,
|
|
3924
|
+
CodexNotificationParams,
|
|
3925
|
+
CodexProtocolError2 as CodexProtocolError,
|
|
3926
|
+
CodexRateLimitSnapshotSchema,
|
|
3927
|
+
CodexRateLimitWindowSchema,
|
|
3928
|
+
CodexRateLimitsResponseSchema,
|
|
3929
|
+
CodexReadThreadResponseSchema,
|
|
3930
|
+
CodexResumeThreadResponseSchema,
|
|
3931
|
+
CodexSandboxModeSchema2 as CodexSandboxModeSchema,
|
|
3932
|
+
CodexSandboxPolicySchema2 as CodexSandboxPolicySchema,
|
|
3532
3933
|
CodexSkillInputSchema,
|
|
3533
|
-
|
|
3934
|
+
CodexSkillsListResponseSchema,
|
|
3935
|
+
CodexThreadContextSchema2 as CodexThreadContextSchema,
|
|
3936
|
+
CodexThreadItemEntrySchema,
|
|
3937
|
+
CodexThreadItemSchema2 as CodexThreadItemSchema,
|
|
3938
|
+
CodexThreadMetadataUpdateResponseSchema,
|
|
3939
|
+
CodexThreadSchema2 as CodexThreadSchema,
|
|
3940
|
+
CodexThreadSourceKindSchema2 as CodexThreadSourceKindSchema,
|
|
3941
|
+
CodexThreadStatusSchema2 as CodexThreadStatusSchema,
|
|
3942
|
+
CodexThreadUnarchiveResponseSchema,
|
|
3943
|
+
CodexThreadUnsubscribeResponseSchema,
|
|
3944
|
+
CodexThreadUnsubscribeStatusSchema,
|
|
3945
|
+
CodexThreadsPageSchema,
|
|
3946
|
+
CodexTurnItemsViewSchema2 as CodexTurnItemsViewSchema,
|
|
3947
|
+
CodexTurnStatusSchema2 as CodexTurnStatusSchema,
|
|
3948
|
+
CodexTurnsPageSchema2 as CodexTurnsPageSchema,
|
|
3949
|
+
CodexUnixSocketError2 as CodexUnixSocketError,
|
|
3534
3950
|
codexFakeScenarios,
|
|
3951
|
+
codexPlanLimits,
|
|
3535
3952
|
codexPlanWindows,
|
|
3536
|
-
createCodexDriver
|
|
3953
|
+
createCodexDriver,
|
|
3954
|
+
findCodexTurnByClientId,
|
|
3955
|
+
iterateCodexPages,
|
|
3956
|
+
parseCodexNotification
|
|
3537
3957
|
};
|