stitchkit 0.130.1 → 0.132.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 +68 -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/transcript.d.ts +1 -1
- package/dist/agent-executor/claude/transcript.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/claude-sdk/session.d.ts.map +1 -1
- package/dist/agent-executor/codex/classify.d.ts.map +1 -1
- package/dist/agent-executor/codex/connect.d.ts +7 -7
- package/dist/agent-executor/codex/connect.d.ts.map +1 -1
- package/dist/agent-executor/codex/control-client.d.ts +86 -99
- 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 +29 -28
- 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 +2 -2
- 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 -148
- 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 +19 -190
- 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 +1 -1
- package/dist/agent-executor/codex/session.d.ts.map +1 -1
- package/dist/agent-executor/codex/shared-server.d.ts +4 -4
- package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
- package/dist/agent-executor/codex/shared-thread.d.ts +5 -5
- package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
- package/dist/agent-executor/codex/thread-controls.d.ts +45 -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 +20 -20
- package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
- package/dist/agent-executor/codex/turn-input.d.ts +4 -3
- 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 +9 -1
- 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 +19 -19
- package/dist/agent-runtime/sql-rows.d.ts +10 -10
- package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
- package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
- package/dist/agent-runtime/terminal-commit.d.ts +10 -10
- package/dist/entrypoints/agent-executor/acp.d.ts +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 +64 -37
- 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 +29 -23
- package/dist/entrypoints/agent-executor/codex.d.ts +9 -5
- package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/codex.js +1860 -1695
- 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/entrypoints/sync.js +8 -4
- package/dist/{index-jrn3prgm.js → index-athc412x.js} +29 -4
- package/dist/{index-dbp6xemn.js → index-f9p62ean.js} +219 -7
- package/dist/index-j15dhkda.js +749 -0
- package/dist/index-jcrj0b8z.js +56 -0
- package/dist/{index-1q0n6zek.js → index-kwsr7j5k.js} +84 -44
- package/dist/{index-p1qmpq0p.js → index-z114ax5e.js} +93 -57
- package/dist/sync/session-machine.d.ts.map +1 -1
- package/dist/sync/session.d.ts +3 -3
- 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 +11 -8
- package/llms/agent-executor-testing.txt +5 -1
- package/llms/agent-executor.txt +10 -4
- package/llms/stitchkit.txt +75 -74
- package/llms/sync.txt +1 -1
- package/llms/{upgrading-0.128.0-0.130.0.txt → upgrading-0.128.0-0.132.0.txt} +76 -3
- package/llms/upgrading.txt +1 -1
- package/llms-full.txt +185 -96
- 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-f9p62ean.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-jcrj0b8z.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-athc412x.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,149 +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
|
-
thread: z.json().optional()
|
|
225
|
-
});
|
|
226
|
-
var CodexInitializeResponseSchema = z.looseObject({
|
|
227
|
-
userAgent: z.string().nullable().optional()
|
|
228
|
-
});
|
|
229
|
-
var CodexStartedThreadSchema = CodexThreadContextSchema.extend({
|
|
230
|
-
thread: z.looseObject({ id: z.string().min(1) })
|
|
231
|
-
}).loose();
|
|
232
|
-
function extractCodexThreadContext(parsed) {
|
|
233
|
-
return {
|
|
234
|
-
...parsed.model !== undefined && { model: parsed.model },
|
|
235
|
-
...parsed.modelProvider !== undefined && { modelProvider: parsed.modelProvider },
|
|
236
|
-
...parsed.reasoningEffort !== undefined && { reasoningEffort: parsed.reasoningEffort },
|
|
237
|
-
...parsed.approvalPolicy !== undefined && { approvalPolicy: parsed.approvalPolicy },
|
|
238
|
-
...parsed.sandbox !== undefined && { sandbox: parsed.sandbox },
|
|
239
|
-
...parsed.cwd !== undefined && { cwd: parsed.cwd },
|
|
240
|
-
...parsed.runtimeWorkspaceRoots !== undefined && {
|
|
241
|
-
runtimeWorkspaceRoots: parsed.runtimeWorkspaceRoots
|
|
242
|
-
},
|
|
243
|
-
thread: safeJsonValue(parsed.thread)
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
var CodexStartedTurnSchema = z.looseObject({
|
|
247
|
-
turn: z.looseObject({ id: z.string().min(1) })
|
|
248
|
-
});
|
|
249
|
-
var CodexTurnSteerResponseSchema = z.looseObject({
|
|
250
|
-
turnId: z.string().min(1)
|
|
251
|
-
});
|
|
252
|
-
var CodexListedTurnItemSchema = z.looseObject({
|
|
253
|
-
type: z.string(),
|
|
254
|
-
clientId: z.string().nullable().optional()
|
|
255
|
-
});
|
|
256
|
-
var CodexListedTurnSchema = CodexTurnSchema.extend({
|
|
257
|
-
items: z.array(CodexListedTurnItemSchema),
|
|
258
|
-
itemsView: z.literal("full").optional()
|
|
259
|
-
});
|
|
260
|
-
var CodexTurnsPageSchema = z.looseObject({
|
|
261
|
-
data: z.array(CodexListedTurnSchema),
|
|
262
|
-
nextCursor: z.string().nullable().optional()
|
|
263
|
-
});
|
|
264
|
-
var CodexThreadRevertResponseSchema = z.looseObject({
|
|
265
|
-
thread: z.looseObject({ id: z.string().min(1) }),
|
|
266
|
-
turnsBackwardsCursor: z.string().nullable().optional(),
|
|
267
|
-
itemsBackwardsCursor: z.string().nullable().optional()
|
|
268
|
-
});
|
|
269
219
|
var CODEX_OPTED_OUT_NOTIFICATIONS = [
|
|
270
220
|
"app/list/updated",
|
|
271
221
|
"item/commandExecution/outputDelta",
|
|
@@ -325,375 +275,399 @@ var CODEX_QUIET_NOTIFICATIONS = new Set([
|
|
|
325
275
|
"modelProvider/authRecoveryCompleted",
|
|
326
276
|
"error"
|
|
327
277
|
]);
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
};
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
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;
|
|
357
353
|
}
|
|
358
354
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
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;
|
|
365
419
|
}
|
|
366
|
-
if (
|
|
367
|
-
|
|
420
|
+
if (item.type === "functionCallOutput") {
|
|
421
|
+
return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
|
|
368
422
|
}
|
|
369
|
-
|
|
423
|
+
return item.type;
|
|
370
424
|
}
|
|
371
|
-
function
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
} catch (error) {
|
|
375
|
-
if (errnoOf(error) === "ENOENT")
|
|
376
|
-
return;
|
|
377
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to inspect unix socket ${label} "${targetPath}"`, { cause: error });
|
|
378
|
-
}
|
|
425
|
+
function toolInput(item) {
|
|
426
|
+
const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
|
|
427
|
+
return safeJsonValue(rest);
|
|
379
428
|
}
|
|
380
|
-
function
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
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]);
|
|
387
435
|
}
|
|
388
|
-
return
|
|
436
|
+
return false;
|
|
389
437
|
}
|
|
390
|
-
function
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
if (
|
|
394
|
-
|
|
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;
|
|
395
444
|
}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
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);
|
|
399
452
|
}
|
|
400
453
|
}
|
|
401
|
-
function
|
|
402
|
-
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
if (stats === undefined)
|
|
409
|
-
return "absent";
|
|
410
|
-
if (requiredUid !== undefined && stats.uid !== requiredUid) {
|
|
411
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket "${socketPath}" is owned by uid ${stats.uid}, expected ${requiredUid}`);
|
|
412
|
-
}
|
|
413
|
-
if (stats.isSymbolicLink()) {
|
|
414
|
-
let resolved;
|
|
415
|
-
try {
|
|
416
|
-
resolved = realpathSync(socketPath);
|
|
417
|
-
} catch (error) {
|
|
418
|
-
if (errnoOf(error) === "ENOENT")
|
|
419
|
-
return "absent";
|
|
420
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to resolve unix socket symlink "${socketPath}"`, { cause: error });
|
|
421
|
-
}
|
|
422
|
-
if (assertPrivateDirStats(dirname(resolved), requiredUid, socketPath, caller) === "absent") {
|
|
423
|
-
return "absent";
|
|
424
|
-
}
|
|
425
|
-
const targetStats = lstatTarget(resolved, "resolved target", socketPath, caller);
|
|
426
|
-
if (targetStats === undefined)
|
|
427
|
-
return "absent";
|
|
428
|
-
if (!targetStats.isSocket()) {
|
|
429
|
-
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is not a socket`);
|
|
430
|
-
}
|
|
431
|
-
if (requiredUid !== undefined && targetStats.uid !== requiredUid) {
|
|
432
|
-
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})`;
|
|
433
461
|
}
|
|
434
|
-
return
|
|
462
|
+
return rawMessage;
|
|
435
463
|
}
|
|
436
|
-
if (
|
|
437
|
-
|
|
464
|
+
if (infoSummary !== undefined) {
|
|
465
|
+
return `Codex ended the turn ${turn.status} (${infoSummary})`;
|
|
438
466
|
}
|
|
439
|
-
return
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
// src/agent-executor/codex/ws-frame.ts
|
|
443
|
-
import { randomBytes } from "node:crypto";
|
|
444
|
-
var MAX_WS_FRAGMENTS = 1024;
|
|
445
|
-
var MAX_CONTROL_PAYLOAD_BYTES = 125;
|
|
446
|
-
function maskedWsFrameByteLength(payloadBytes) {
|
|
447
|
-
const headerLen = payloadBytes < 126 ? 2 : payloadBytes <= 65535 ? 4 : 10;
|
|
448
|
-
return headerLen + 4 + payloadBytes;
|
|
449
|
-
}
|
|
450
|
-
function encodeMaskedWsFrame(opcode, payload) {
|
|
451
|
-
const len = payload.byteLength;
|
|
452
|
-
const headerLen = len < 126 ? 2 : len <= 65535 ? 4 : 10;
|
|
453
|
-
const frame = Buffer.allocUnsafe(headerLen + 4 + len);
|
|
454
|
-
frame[0] = 128 | opcode & 15;
|
|
455
|
-
if (len < 126) {
|
|
456
|
-
frame[1] = 128 | len;
|
|
457
|
-
} else if (len <= 65535) {
|
|
458
|
-
frame[1] = 128 | 126;
|
|
459
|
-
frame.writeUInt16BE(len, 2);
|
|
460
|
-
} else {
|
|
461
|
-
frame[1] = 128 | 127;
|
|
462
|
-
const hi = Math.floor(len / 4294967296);
|
|
463
|
-
const lo = len >>> 0;
|
|
464
|
-
frame.writeUInt32BE(hi, 2);
|
|
465
|
-
frame.writeUInt32BE(lo, 6);
|
|
466
|
-
}
|
|
467
|
-
const mask = randomBytes(4);
|
|
468
|
-
frame[headerLen] = mask[0] ?? 0;
|
|
469
|
-
frame[headerLen + 1] = mask[1] ?? 0;
|
|
470
|
-
frame[headerLen + 2] = mask[2] ?? 0;
|
|
471
|
-
frame[headerLen + 3] = mask[3] ?? 0;
|
|
472
|
-
const bodyOffset = headerLen + 4;
|
|
473
|
-
for (let i = 0;i < len; i += 1) {
|
|
474
|
-
frame[bodyOffset + i] = (payload[i] ?? 0) ^ (mask[i & 3] ?? 0);
|
|
475
|
-
}
|
|
476
|
-
return frame;
|
|
477
|
-
}
|
|
478
|
-
function createByteQueue() {
|
|
479
|
-
const chunks = [];
|
|
480
|
-
let headOffset = 0;
|
|
481
|
-
let total = 0;
|
|
482
|
-
return {
|
|
483
|
-
get length() {
|
|
484
|
-
return total;
|
|
485
|
-
},
|
|
486
|
-
push(chunk) {
|
|
487
|
-
if (chunk.byteLength === 0)
|
|
488
|
-
return;
|
|
489
|
-
chunks.push(chunk);
|
|
490
|
-
total += chunk.byteLength;
|
|
491
|
-
},
|
|
492
|
-
peekBytes(count) {
|
|
493
|
-
const first = chunks[0];
|
|
494
|
-
if (first !== undefined && first.byteLength - headOffset >= count) {
|
|
495
|
-
return first.subarray(headOffset, headOffset + count);
|
|
496
|
-
}
|
|
497
|
-
const out = Buffer.allocUnsafe(count);
|
|
498
|
-
let written = 0;
|
|
499
|
-
let idx = 0;
|
|
500
|
-
let off = headOffset;
|
|
501
|
-
while (written < count && idx < chunks.length) {
|
|
502
|
-
const cur = chunks[idx];
|
|
503
|
-
if (cur === undefined)
|
|
504
|
-
break;
|
|
505
|
-
const take = Math.min(cur.byteLength - off, count - written);
|
|
506
|
-
cur.copy(out, written, off, off + take);
|
|
507
|
-
written += take;
|
|
508
|
-
idx += 1;
|
|
509
|
-
off = 0;
|
|
510
|
-
}
|
|
511
|
-
return out;
|
|
512
|
-
},
|
|
513
|
-
consume(count) {
|
|
514
|
-
const out = Buffer.allocUnsafe(count);
|
|
515
|
-
let written = 0;
|
|
516
|
-
while (written < count && chunks.length > 0) {
|
|
517
|
-
const cur = chunks[0];
|
|
518
|
-
if (cur === undefined)
|
|
519
|
-
break;
|
|
520
|
-
const avail = cur.byteLength - headOffset;
|
|
521
|
-
const take = Math.min(avail, count - written);
|
|
522
|
-
cur.copy(out, written, headOffset, headOffset + take);
|
|
523
|
-
written += take;
|
|
524
|
-
total -= take;
|
|
525
|
-
if (take === avail) {
|
|
526
|
-
chunks.shift();
|
|
527
|
-
headOffset = 0;
|
|
528
|
-
} else {
|
|
529
|
-
headOffset += take;
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
return out;
|
|
533
|
-
},
|
|
534
|
-
skip(count) {
|
|
535
|
-
let left = count;
|
|
536
|
-
while (left > 0 && chunks.length > 0) {
|
|
537
|
-
const cur = chunks[0];
|
|
538
|
-
if (cur === undefined)
|
|
539
|
-
break;
|
|
540
|
-
const avail = cur.byteLength - headOffset;
|
|
541
|
-
if (left >= avail) {
|
|
542
|
-
chunks.shift();
|
|
543
|
-
headOffset = 0;
|
|
544
|
-
total -= avail;
|
|
545
|
-
left -= avail;
|
|
546
|
-
} else {
|
|
547
|
-
headOffset += left;
|
|
548
|
-
total -= left;
|
|
549
|
-
left = 0;
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
},
|
|
553
|
-
clear() {
|
|
554
|
-
chunks.length = 0;
|
|
555
|
-
headOffset = 0;
|
|
556
|
-
total = 0;
|
|
557
|
-
}
|
|
558
|
-
};
|
|
467
|
+
return `Codex ended the turn ${turn.status}`;
|
|
559
468
|
}
|
|
560
|
-
function
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
const
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
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`
|
|
655
576
|
}
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
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)
|
|
669
591
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
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)
|
|
687
613
|
}
|
|
688
|
-
handlers.onMessage(text);
|
|
689
614
|
}
|
|
690
|
-
|
|
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
|
+
});
|
|
691
631
|
}
|
|
632
|
+
deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
|
|
633
|
+
return { kind: "end", deltas, outcome };
|
|
692
634
|
}
|
|
693
|
-
|
|
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
|
+
}
|
|
694
667
|
}
|
|
695
|
-
|
|
696
668
|
// src/agent-executor/codex/unix-socket.ts
|
|
669
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
670
|
+
import { createConnection } from "node:net";
|
|
697
671
|
var WS_MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
698
672
|
var MAX_HANDSHAKE_HEADER_BYTES = 64 * 1024;
|
|
699
673
|
var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15000;
|
|
@@ -705,7 +679,7 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
|
|
|
705
679
|
`);
|
|
706
680
|
const statusLine = lines[0] ?? "";
|
|
707
681
|
if (!/^HTTP\/1\.1 101(?:\s|$)/.test(statusLine)) {
|
|
708
|
-
throw new
|
|
682
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, `Codex Unix socket WebSocket upgrade failed: ${statusLine || "empty response"}`);
|
|
709
683
|
}
|
|
710
684
|
const headers = new Map;
|
|
711
685
|
for (let i = 1;i < lines.length; i += 1) {
|
|
@@ -714,7 +688,7 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
|
|
|
714
688
|
continue;
|
|
715
689
|
const colon = line.indexOf(":");
|
|
716
690
|
if (colon <= 0) {
|
|
717
|
-
throw new
|
|
691
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, "Codex Unix socket upgrade response contained a malformed HTTP header line");
|
|
718
692
|
}
|
|
719
693
|
const key = line.slice(0, colon).trim().toLowerCase();
|
|
720
694
|
const value = line.slice(colon + 1).trim();
|
|
@@ -722,30 +696,30 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
|
|
|
722
696
|
headers.set(key, existing === undefined ? value : `${existing}, ${value}`);
|
|
723
697
|
}
|
|
724
698
|
if ((headers.get("upgrade") ?? "").toLowerCase() !== "websocket") {
|
|
725
|
-
throw new
|
|
699
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Upgrade: websocket" header');
|
|
726
700
|
}
|
|
727
701
|
const connectionTokens = (headers.get("connection") ?? "").toLowerCase().split(",").map((token) => token.trim());
|
|
728
702
|
if (!connectionTokens.includes("upgrade")) {
|
|
729
|
-
throw new
|
|
703
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Connection: upgrade" header');
|
|
730
704
|
}
|
|
731
705
|
if (headers.get("sec-websocket-accept") !== expectedAccept) {
|
|
732
|
-
throw new
|
|
706
|
+
throw new CodexUnixSocketError2("upgrade-refused", socketPath, "Codex Unix socket upgrade response returned an invalid Sec-WebSocket-Accept header");
|
|
733
707
|
}
|
|
734
708
|
}
|
|
735
709
|
function classifyConnectError(error, socketPath) {
|
|
736
710
|
const code = errnoOf(error);
|
|
737
711
|
if (code === "ENOENT") {
|
|
738
|
-
return new
|
|
712
|
+
return new CodexUnixSocketError2("endpoint-absent", socketPath, `Codex Unix socket "${socketPath}" does not exist`, { cause: error });
|
|
739
713
|
}
|
|
740
714
|
if (code === "ECONNREFUSED") {
|
|
741
|
-
return new
|
|
715
|
+
return new CodexUnixSocketError2("endpoint-not-listening", socketPath, `Codex Unix socket "${socketPath}" refused connection`, { cause: error });
|
|
742
716
|
}
|
|
743
|
-
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 });
|
|
744
718
|
}
|
|
745
719
|
function performWsUpgrade(input) {
|
|
746
|
-
const wsKey =
|
|
720
|
+
const wsKey = randomBytes(16).toString("base64");
|
|
747
721
|
const expectedAccept = createHash("sha1").update(`${wsKey}${WS_MAGIC_GUID}`).digest("base64");
|
|
748
|
-
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) => {
|
|
749
723
|
let settled = false;
|
|
750
724
|
let handshakeBuf = Buffer.alloc(0);
|
|
751
725
|
const sock = createConnection({ path: input.socketPath });
|
|
@@ -778,7 +752,7 @@ Sec-WebSocket-Version: 13\r
|
|
|
778
752
|
const onData = (chunk) => {
|
|
779
753
|
const combinedLen = handshakeBuf.byteLength + chunk.byteLength;
|
|
780
754
|
if (handshakeBuf.byteLength > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
781
|
-
fail(new
|
|
755
|
+
fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
782
756
|
return;
|
|
783
757
|
}
|
|
784
758
|
const nextBuf = handshakeBuf.byteLength === 0 ? chunk : Buffer.concat([handshakeBuf, chunk]);
|
|
@@ -787,14 +761,14 @@ Sec-WebSocket-Version: 13\r
|
|
|
787
761
|
`);
|
|
788
762
|
if (boundary === -1) {
|
|
789
763
|
if (combinedLen > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
790
|
-
fail(new
|
|
764
|
+
fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
791
765
|
return;
|
|
792
766
|
}
|
|
793
767
|
handshakeBuf = nextBuf;
|
|
794
768
|
return;
|
|
795
769
|
}
|
|
796
770
|
if (boundary > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
797
|
-
fail(new
|
|
771
|
+
fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
798
772
|
return;
|
|
799
773
|
}
|
|
800
774
|
const headerText = nextBuf.subarray(0, boundary).toString("latin1");
|
|
@@ -811,7 +785,7 @@ Sec-WebSocket-Version: 13\r
|
|
|
811
785
|
resolve({ socket: sock, trailing: rest });
|
|
812
786
|
};
|
|
813
787
|
const onError = (error) => fail(classifyConnectError(error, input.socketPath));
|
|
814
|
-
const onClose = () => fail(new
|
|
788
|
+
const onClose = () => fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, "Codex Unix socket closed before completing WebSocket upgrade"));
|
|
815
789
|
handshakeSignal.addEventListener("abort", onAbort, { once: true });
|
|
816
790
|
sock.once("connect", onConnect);
|
|
817
791
|
sock.on("data", onData);
|
|
@@ -828,7 +802,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
828
802
|
input.connectSignal?.throwIfAborted();
|
|
829
803
|
const targetState = assertCodexUnixSocketClientTarget(input.socketPath, "connectCodexUnixSocket", input.expectedOwnerUid);
|
|
830
804
|
if (targetState === "absent") {
|
|
831
|
-
throw new
|
|
805
|
+
throw new CodexUnixSocketError2("endpoint-absent", input.socketPath, `Codex Unix socket "${input.socketPath}" does not exist`);
|
|
832
806
|
}
|
|
833
807
|
const maxFrameBytes = input.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
|
|
834
808
|
const maxPendingWriteBytes = input.maxPendingWriteBytes ?? DEFAULT_MAX_PENDING_WRITE_BYTES;
|
|
@@ -842,7 +816,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
842
816
|
throw abortReason(input.signal);
|
|
843
817
|
}
|
|
844
818
|
if (socket.destroyed) {
|
|
845
|
-
throw new
|
|
819
|
+
throw new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed during WebSocket upgrade`);
|
|
846
820
|
}
|
|
847
821
|
let closed = false;
|
|
848
822
|
let closeSent = false;
|
|
@@ -887,7 +861,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
887
861
|
}
|
|
888
862
|
};
|
|
889
863
|
const onSignalAbort = () => {
|
|
890
|
-
const err = new
|
|
864
|
+
const err = new CodexUnixSocketError2("connection-lost", input.socketPath, "Codex Unix socket connection aborted", { cause: abortReason(input.signal) });
|
|
891
865
|
socket.destroy();
|
|
892
866
|
finishClosed(err);
|
|
893
867
|
};
|
|
@@ -903,20 +877,20 @@ async function connectCodexUnixSocket(input) {
|
|
|
903
877
|
}
|
|
904
878
|
socket.end();
|
|
905
879
|
const suffix = reason.length > 0 ? `: ${reason}` : "";
|
|
906
|
-
finishClosed(new
|
|
880
|
+
finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket closed by peer (${code ?? "no-code"})${suffix}`));
|
|
907
881
|
},
|
|
908
882
|
onProtocolError: (message) => {
|
|
909
|
-
const err = new
|
|
883
|
+
const err = new CodexUnixSocketError2("connection-lost", input.socketPath, message);
|
|
910
884
|
socket.destroy();
|
|
911
885
|
finishClosed(err);
|
|
912
886
|
}
|
|
913
887
|
});
|
|
914
888
|
socket.on("data", (chunk) => decoder.push(chunk));
|
|
915
889
|
socket.on("error", (error) => {
|
|
916
|
-
finishClosed(new
|
|
890
|
+
finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket error: ${error.message}`, { cause: error }));
|
|
917
891
|
});
|
|
918
892
|
socket.on("close", () => {
|
|
919
|
-
finishClosed(new
|
|
893
|
+
finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed`));
|
|
920
894
|
});
|
|
921
895
|
if (trailing.byteLength > 0)
|
|
922
896
|
decoder.push(trailing);
|
|
@@ -925,7 +899,7 @@ async function connectCodexUnixSocket(input) {
|
|
|
925
899
|
return {
|
|
926
900
|
send(text) {
|
|
927
901
|
if (closed || socket.destroyed || !socket.writable) {
|
|
928
|
-
throw new
|
|
902
|
+
throw new CodexUnixSocketError2("connection-lost", input.socketPath, "Codex Unix socket connection is closed");
|
|
929
903
|
}
|
|
930
904
|
const payloadBytes = Buffer.byteLength(text, "utf8");
|
|
931
905
|
const frameBytes = maskedWsFrameByteLength(payloadBytes);
|
|
@@ -985,7 +959,7 @@ async function initializeCodexPeer(peer, version) {
|
|
|
985
959
|
optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
|
|
986
960
|
}
|
|
987
961
|
}, { timeoutMs: BOOTSTRAP_MS });
|
|
988
|
-
const parsed = CodexInitializeResponseSchema
|
|
962
|
+
const parsed = parseCodexResponse("initialize", CodexInitializeResponseSchema, reply);
|
|
989
963
|
peer.notify("initialized");
|
|
990
964
|
return nonEmptyString(parsed.userAgent);
|
|
991
965
|
}
|
|
@@ -1016,7 +990,7 @@ async function dialWithEngineRace(input) {
|
|
|
1016
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 });
|
|
1017
991
|
exitAbort.abort(exitedEarly);
|
|
1018
992
|
});
|
|
1019
|
-
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) => {
|
|
1020
994
|
let delayMs = POLL_INITIAL_MS;
|
|
1021
995
|
for (;; ) {
|
|
1022
996
|
if (exitedEarly !== undefined)
|
|
@@ -1038,7 +1012,7 @@ async function dialWithEngineRace(input) {
|
|
|
1038
1012
|
} catch (error) {
|
|
1039
1013
|
if (exitedEarly !== undefined)
|
|
1040
1014
|
throw exitedEarly;
|
|
1041
|
-
const retryable = error instanceof
|
|
1015
|
+
const retryable = error instanceof CodexUnixSocketError2 && (error.kind === "endpoint-absent" || error.kind === "endpoint-not-listening");
|
|
1042
1016
|
if (!retryable)
|
|
1043
1017
|
throw error;
|
|
1044
1018
|
await raceAbort(sleepAbortable(delayMs, deadlineSignal), exitAbort.signal);
|
|
@@ -1231,139 +1205,204 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
|
|
|
1231
1205
|
}
|
|
1232
1206
|
}
|
|
1233
1207
|
|
|
1234
|
-
// src/agent-executor/codex/
|
|
1208
|
+
// src/agent-executor/codex/responses.ts
|
|
1235
1209
|
import { z as z2 } from "zod";
|
|
1236
|
-
var
|
|
1237
|
-
var
|
|
1238
|
-
var
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
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()
|
|
1234
|
+
});
|
|
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)
|
|
1242
1292
|
});
|
|
1243
|
-
var
|
|
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({
|
|
1244
1364
|
limitId: z2.string().nullable().optional(),
|
|
1245
1365
|
limitName: z2.string().nullable().optional(),
|
|
1246
|
-
|
|
1247
|
-
|
|
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()
|
|
1248
1374
|
});
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
...label !== undefined && { label }
|
|
1281
|
-
}));
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
function isPlainRecord(value) {
|
|
1285
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1286
|
-
}
|
|
1287
|
-
function codexPlanWindows(reported) {
|
|
1288
|
-
const windows = [];
|
|
1289
|
-
const seenNames = new Set;
|
|
1290
|
-
if (isPlainRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported))) {
|
|
1291
|
-
const seenLimitIds = new Set;
|
|
1292
|
-
const rawById = reported.rateLimitsByLimitId;
|
|
1293
|
-
if (isPlainRecord(rawById)) {
|
|
1294
|
-
for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
|
|
1295
|
-
const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
|
|
1296
|
-
if (!parsed.success)
|
|
1297
|
-
continue;
|
|
1298
|
-
const limitId = nonEmptyString(parsed.data.limitId)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
|
|
1299
|
-
seenLimitIds.add(limitId);
|
|
1300
|
-
appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
|
|
1301
|
-
if (windows.length >= MAX_PLAN_WINDOWS)
|
|
1302
|
-
return windows;
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
if (windows.length < MAX_PLAN_WINDOWS && reported.rateLimits !== undefined) {
|
|
1306
|
-
const parsedSingle = SnapshotSchema.safeParse(reported.rateLimits);
|
|
1307
|
-
if (parsedSingle.success) {
|
|
1308
|
-
const explicitId = nonEmptyString(parsedSingle.data.limitId)?.trim();
|
|
1309
|
-
const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
|
|
1310
|
-
if (shouldIncludeSingle) {
|
|
1311
|
-
appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1315
|
-
return windows;
|
|
1316
|
-
}
|
|
1317
|
-
const single = SnapshotSchema.safeParse(reported);
|
|
1318
|
-
if (!single.success)
|
|
1319
|
-
return [];
|
|
1320
|
-
const limitId = nonEmptyString(single.data.limitId)?.trim() ?? "limit";
|
|
1321
|
-
appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
|
|
1322
|
-
return windows;
|
|
1323
|
-
}
|
|
1324
|
-
|
|
1325
|
-
// src/agent-executor/codex/thread-controls.ts
|
|
1326
|
-
var MAX_UINT32 = 4294967295;
|
|
1327
|
-
var MAX_THREAD_LIST_IDS = 100;
|
|
1328
|
-
function assertNonEmptyThreadId(threadId, caller) {
|
|
1329
|
-
if (typeof threadId !== "string" || threadId.trim().length === 0) {
|
|
1330
|
-
throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
|
|
1331
|
-
}
|
|
1332
|
-
return threadId;
|
|
1333
|
-
}
|
|
1334
|
-
function assertRequiredNonEmptyString(value, field, caller) {
|
|
1335
|
-
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1336
|
-
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1337
|
-
}
|
|
1338
|
-
return value;
|
|
1339
|
-
}
|
|
1340
|
-
function assertOptionalNonEmptyString(value, field, caller) {
|
|
1341
|
-
if (value === undefined)
|
|
1342
|
-
return;
|
|
1343
|
-
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1344
|
-
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
function assertOptionalNonEmptyNoNulString(value, field, caller) {
|
|
1348
|
-
if (value === undefined)
|
|
1349
|
-
return;
|
|
1350
|
-
if (typeof value !== "string" || value.trim().length === 0 || value.includes("\x00")) {
|
|
1351
|
-
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string without NUL bytes`);
|
|
1352
|
-
}
|
|
1353
|
-
}
|
|
1354
|
-
function assertOptionalLimit(limit, caller) {
|
|
1355
|
-
if (limit === undefined || limit === null)
|
|
1356
|
-
return;
|
|
1357
|
-
assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
|
|
1358
|
-
if (limit > MAX_UINT32) {
|
|
1359
|
-
throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
function assertBoundedThreadIdFilter(ids, field, caller) {
|
|
1363
|
-
if (ids === undefined || ids === null)
|
|
1364
|
-
return ids;
|
|
1365
|
-
if (!Array.isArray(ids)) {
|
|
1366
|
-
throw new TypeError(`[stitchkit] ${caller}: ${field} must be an array of strings`);
|
|
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
|
|
1397
|
+
});
|
|
1398
|
+
|
|
1399
|
+
// src/agent-executor/codex/thread-list-query.ts
|
|
1400
|
+
var MAX_THREAD_LIST_IDS = 100;
|
|
1401
|
+
function assertBoundedThreadIdFilter(ids, field, caller) {
|
|
1402
|
+
if (ids === undefined || ids === null)
|
|
1403
|
+
return ids;
|
|
1404
|
+
if (!Array.isArray(ids)) {
|
|
1405
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be an array of strings`);
|
|
1367
1406
|
}
|
|
1368
1407
|
if (ids.length > MAX_THREAD_LIST_IDS) {
|
|
1369
1408
|
throw new TypeError(`[stitchkit] ${caller}: ${field} must contain at most ${MAX_THREAD_LIST_IDS} entries`);
|
|
@@ -1440,364 +1479,268 @@ function buildListThreadsPayload(params) {
|
|
|
1440
1479
|
...params?.useStateDbOnly !== undefined && { useStateDbOnly: params.useStateDbOnly }
|
|
1441
1480
|
};
|
|
1442
1481
|
}
|
|
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
|
+
}
|
|
1443
1529
|
function createCodexThreadControlMethods(call, options = {}) {
|
|
1444
1530
|
return {
|
|
1445
|
-
async revertThread(params) {
|
|
1531
|
+
async revertThread(params, rpcOptions) {
|
|
1446
1532
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.revertThread");
|
|
1447
1533
|
const beforeTurnId = assertRequiredNonEmptyString(params.beforeTurnId, "beforeTurnId", "CodexControlClient.revertThread");
|
|
1448
|
-
const rawReply = await call("thread/revert", { threadId, beforeTurnId });
|
|
1449
|
-
const parsed = CodexThreadRevertResponseSchema
|
|
1534
|
+
const rawReply = await call("thread/revert", { threadId, beforeTurnId }, rpcOptions);
|
|
1535
|
+
const parsed = parseCodexResponse("thread/revert", CodexThreadRevertResponseSchema, rawReply);
|
|
1450
1536
|
return {
|
|
1451
|
-
thread:
|
|
1537
|
+
thread: parsed.thread,
|
|
1452
1538
|
turnsBackwardsCursor: parsed.turnsBackwardsCursor ?? null,
|
|
1453
1539
|
itemsBackwardsCursor: parsed.itemsBackwardsCursor ?? null
|
|
1454
1540
|
};
|
|
1455
1541
|
},
|
|
1456
|
-
async injectItems(params) {
|
|
1542
|
+
async injectItems(params, rpcOptions) {
|
|
1457
1543
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.injectItems");
|
|
1458
1544
|
if (!Array.isArray(params.items)) {
|
|
1459
1545
|
throw new TypeError("[stitchkit] CodexControlClient.injectItems: items must be an array");
|
|
1460
1546
|
}
|
|
1461
1547
|
const items = params.items.map((item) => safeJsonValue(item));
|
|
1462
|
-
|
|
1548
|
+
const raw = await call("thread/inject_items", { threadId, items }, rpcOptions);
|
|
1549
|
+
parseCodexResponse("thread/inject_items", CodexEmptyResponseSchema, raw);
|
|
1463
1550
|
},
|
|
1464
|
-
async unsubscribeThread(params) {
|
|
1551
|
+
async unsubscribeThread(params, rpcOptions) {
|
|
1465
1552
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unsubscribeThread");
|
|
1466
|
-
return call("thread/unsubscribe", { threadId });
|
|
1553
|
+
return parseCodexResponse("thread/unsubscribe", CodexThreadUnsubscribeResponseSchema, await call("thread/unsubscribe", { threadId }, rpcOptions));
|
|
1467
1554
|
},
|
|
1468
|
-
async listThreads(params) {
|
|
1469
|
-
return call("thread/list", buildListThreadsPayload(params));
|
|
1555
|
+
async listThreads(params, rpcOptions) {
|
|
1556
|
+
return parseCodexResponse("thread/list", CodexThreadsPageSchema, await call("thread/list", buildListThreadsPayload(params), rpcOptions));
|
|
1470
1557
|
},
|
|
1471
|
-
async listLoadedThreads(params) {
|
|
1558
|
+
async listLoadedThreads(params, rpcOptions) {
|
|
1472
1559
|
assertOptionalLimit(params?.limit, "CodexControlClient.listLoadedThreads");
|
|
1473
|
-
return call("thread/loaded/list", {
|
|
1560
|
+
return parseCodexResponse("thread/loaded/list", CodexLoadedThreadsPageSchema, await call("thread/loaded/list", {
|
|
1474
1561
|
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1475
1562
|
...params?.limit !== undefined && { limit: params.limit }
|
|
1476
|
-
});
|
|
1563
|
+
}, rpcOptions));
|
|
1477
1564
|
},
|
|
1478
|
-
async archiveThread(params) {
|
|
1565
|
+
async archiveThread(params, rpcOptions) {
|
|
1479
1566
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.archiveThread");
|
|
1480
|
-
|
|
1567
|
+
const raw = await call("thread/archive", { threadId }, rpcOptions);
|
|
1568
|
+
parseCodexResponse("thread/archive", CodexEmptyResponseSchema, raw);
|
|
1481
1569
|
},
|
|
1482
|
-
async unarchiveThread(params) {
|
|
1570
|
+
async unarchiveThread(params, rpcOptions) {
|
|
1483
1571
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unarchiveThread");
|
|
1484
|
-
return call("thread/unarchive", { threadId });
|
|
1572
|
+
return parseCodexResponse("thread/unarchive", CodexThreadUnarchiveResponseSchema, await call("thread/unarchive", { threadId }, rpcOptions));
|
|
1485
1573
|
},
|
|
1486
|
-
async updateThreadMetadata(params) {
|
|
1574
|
+
async updateThreadMetadata(params, rpcOptions) {
|
|
1487
1575
|
const caller = "CodexControlClient.updateThreadMetadata";
|
|
1488
1576
|
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1489
1577
|
const gitInfo = validateGitInfoUpdate(params.gitInfo, caller);
|
|
1490
|
-
return call("thread/metadata/update", {
|
|
1578
|
+
return parseCodexResponse("thread/metadata/update", CodexThreadMetadataUpdateResponseSchema, await call("thread/metadata/update", {
|
|
1491
1579
|
threadId,
|
|
1492
1580
|
...gitInfo !== undefined && { gitInfo }
|
|
1493
|
-
});
|
|
1581
|
+
}, rpcOptions));
|
|
1494
1582
|
},
|
|
1495
|
-
async setThreadName(params) {
|
|
1583
|
+
async setThreadName(params, rpcOptions) {
|
|
1496
1584
|
const caller = "CodexControlClient.setThreadName";
|
|
1497
1585
|
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1498
1586
|
const name = assertRequiredNonEmptyString(params.name, "name", caller);
|
|
1499
|
-
|
|
1587
|
+
const raw = await call("thread/name/set", { threadId, name }, rpcOptions);
|
|
1588
|
+
parseCodexResponse("thread/name/set", CodexEmptyResponseSchema, raw);
|
|
1500
1589
|
},
|
|
1501
|
-
async interruptTurn(params) {
|
|
1590
|
+
async interruptTurn(params, rpcOptions) {
|
|
1502
1591
|
options.ensureAlive?.();
|
|
1592
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1503
1593
|
const caller = "CodexControlClient.interruptTurn";
|
|
1504
1594
|
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1505
1595
|
const turnId = assertRequiredNonEmptyString(params.turnId, "turnId", caller);
|
|
1506
1596
|
options.onBeforeInterruptTurn?.(threadId, turnId);
|
|
1507
|
-
await call("turn/interrupt", { threadId, turnId });
|
|
1597
|
+
await call("turn/interrupt", { threadId, turnId }, rpcOptions);
|
|
1508
1598
|
},
|
|
1509
|
-
async compactThread(params) {
|
|
1599
|
+
async compactThread(params, rpcOptions) {
|
|
1510
1600
|
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.compactThread");
|
|
1511
|
-
await call("thread/compact/start", { threadId });
|
|
1601
|
+
await call("thread/compact/start", { threadId }, rpcOptions);
|
|
1512
1602
|
}
|
|
1513
1603
|
};
|
|
1514
1604
|
}
|
|
1515
1605
|
|
|
1516
|
-
// src/agent-executor/codex/
|
|
1517
|
-
function
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
const nested = nonEmptyString(Reflect.get(turn, "id"));
|
|
1529
|
-
if (nested !== undefined)
|
|
1530
|
-
return nested;
|
|
1606
|
+
// src/agent-executor/codex/control-read-methods.ts
|
|
1607
|
+
function assertOptionalItemsCursor(cursor, caller) {
|
|
1608
|
+
if (cursor === undefined || cursor === null || cursor === "")
|
|
1609
|
+
return;
|
|
1610
|
+
if (typeof cursor === "string") {
|
|
1611
|
+
if (cursor.trim().length === 0) {
|
|
1612
|
+
throw new TypeError(`[stitchkit] ${caller}: item cursor cannot be whitespace-only`);
|
|
1613
|
+
}
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
if (typeof cursor !== "object" || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
|
|
1617
|
+
throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
|
|
1531
1618
|
}
|
|
1532
|
-
return "external";
|
|
1533
1619
|
}
|
|
1534
|
-
function
|
|
1535
|
-
const asked = CodexApprovalParamsSchema.parse(params);
|
|
1536
|
-
const callId = nonEmptyString(asked.itemId);
|
|
1537
|
-
const metadata = {};
|
|
1538
|
-
if (typeof asked.command === "string")
|
|
1539
|
-
metadata.command = asked.command;
|
|
1540
|
-
if (typeof asked.cwd === "string")
|
|
1541
|
-
metadata.cwd = asked.cwd;
|
|
1542
|
-
if (typeof asked.reason === "string")
|
|
1543
|
-
metadata.reason = asked.reason;
|
|
1544
|
-
if (typeof asked.grantRoot === "string")
|
|
1545
|
-
metadata.grantRoot = asked.grantRoot;
|
|
1546
|
-
if (typeof asked.kind === "string")
|
|
1547
|
-
metadata.kind = asked.kind;
|
|
1548
|
-
if (typeof asked.approvalId === "string")
|
|
1549
|
-
metadata.approvalId = asked.approvalId;
|
|
1550
|
-
if (asked.commandActions != null)
|
|
1551
|
-
metadata.commandActions = asked.commandActions;
|
|
1552
|
-
if (asked.availableDecisions != null)
|
|
1553
|
-
metadata.availableDecisions = asked.availableDecisions;
|
|
1554
|
-
const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
|
|
1555
|
-
const detail = {
|
|
1556
|
-
method,
|
|
1557
|
-
...typeof asked.kind === "string" && { kind: asked.kind },
|
|
1558
|
-
...Array.isArray(asked.availableDecisions) && {
|
|
1559
|
-
availableDecisions: asked.availableDecisions
|
|
1560
|
-
}
|
|
1561
|
-
};
|
|
1620
|
+
function createCodexReadMethods(call) {
|
|
1562
1621
|
return {
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1622
|
+
async readConfig(params, rpcOptions) {
|
|
1623
|
+
return parseCodexResponse("config/read", CodexConfigReadResponseSchema, await call("config/read", {
|
|
1624
|
+
...params?.cwd !== undefined && { cwd: params.cwd },
|
|
1625
|
+
...params?.includeLayers !== undefined && {
|
|
1626
|
+
includeLayers: params.includeLayers
|
|
1627
|
+
}
|
|
1628
|
+
}, rpcOptions));
|
|
1629
|
+
},
|
|
1630
|
+
async readThread(params, rpcOptions) {
|
|
1631
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
|
|
1632
|
+
return parseCodexResponse("thread/read", CodexReadThreadResponseSchema, await call("thread/read", {
|
|
1633
|
+
threadId,
|
|
1634
|
+
...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
|
|
1635
|
+
}, rpcOptions));
|
|
1636
|
+
},
|
|
1637
|
+
async listCollaborationModes(rpcOptions) {
|
|
1638
|
+
return parseCodexResponse("collaborationMode/list", CodexCollaborationModesResponseSchema, await call("collaborationMode/list", {}, rpcOptions));
|
|
1639
|
+
},
|
|
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", {
|
|
1648
|
+
threadId,
|
|
1649
|
+
...params.cursor !== undefined && { cursor: params.cursor },
|
|
1650
|
+
...params.limit !== undefined && { limit: params.limit },
|
|
1651
|
+
...params.itemsView !== undefined && { itemsView: params.itemsView },
|
|
1652
|
+
...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
|
|
1653
|
+
}, rpcOptions));
|
|
1654
|
+
},
|
|
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", {
|
|
1662
|
+
threadId,
|
|
1663
|
+
...params.turnId !== undefined && { turnId: params.turnId },
|
|
1664
|
+
...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
|
|
1665
|
+
...params.limit !== undefined && { limit: params.limit },
|
|
1666
|
+
...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
|
|
1667
|
+
...params.deferOutput !== undefined && {
|
|
1668
|
+
deferOutput: safeJsonValue(params.deferOutput)
|
|
1669
|
+
}
|
|
1670
|
+
}, rpcOptions));
|
|
1671
|
+
},
|
|
1672
|
+
async listMcpServerStatus(params, rpcOptions) {
|
|
1673
|
+
return parseCodexResponse("mcpServerStatus/list", CodexMcpServerStatusPageSchema, await call("mcpServerStatus/list", {
|
|
1674
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1675
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
1676
|
+
...params?.threadId !== undefined && { threadId: params.threadId },
|
|
1677
|
+
...params?.serverName !== undefined && { serverName: params.serverName },
|
|
1678
|
+
...params?.detail !== undefined && { detail: params.detail }
|
|
1679
|
+
}, rpcOptions));
|
|
1680
|
+
},
|
|
1681
|
+
async listSkills(params, rpcOptions) {
|
|
1682
|
+
return parseCodexResponse("skills/list", CodexSkillsListResponseSchema, await call("skills/list", {
|
|
1683
|
+
...params?.cwds !== undefined && { cwds: [...params.cwds] },
|
|
1684
|
+
...params?.forceReload !== undefined && { forceReload: params.forceReload }
|
|
1685
|
+
}, rpcOptions));
|
|
1686
|
+
},
|
|
1687
|
+
async listModels(params, rpcOptions) {
|
|
1688
|
+
return parseCodexResponse("model/list", CodexModelsPageSchema, await call("model/list", {
|
|
1689
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1690
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
1691
|
+
...params?.includeHidden !== undefined && {
|
|
1692
|
+
includeHidden: params.includeHidden
|
|
1693
|
+
},
|
|
1694
|
+
...params?.modelProvider !== undefined && {
|
|
1695
|
+
modelProvider: params.modelProvider
|
|
1696
|
+
}
|
|
1697
|
+
}, rpcOptions));
|
|
1698
|
+
},
|
|
1699
|
+
async readAccount(params, rpcOptions) {
|
|
1700
|
+
return parseCodexResponse("account/read", CodexAccountReadResponseSchema, await call("account/read", {
|
|
1701
|
+
...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
|
|
1702
|
+
}, rpcOptions));
|
|
1703
|
+
},
|
|
1704
|
+
async readRateLimits(rpcOptions) {
|
|
1705
|
+
return parseCodexResponse("account/rateLimits/read", CodexRateLimitsResponseSchema, await call("account/rateLimits/read", undefined, rpcOptions));
|
|
1568
1706
|
}
|
|
1569
1707
|
};
|
|
1570
1708
|
}
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
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");
|
|
1593
1733
|
}
|
|
1594
|
-
|
|
1595
|
-
}
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
permissions,
|
|
1605
|
-
startedAtMs: asked.startedAtMs
|
|
1606
|
-
};
|
|
1607
|
-
if (typeof asked.reason === "string")
|
|
1608
|
-
metadata.reason = asked.reason;
|
|
1609
|
-
if (typeof asked.environmentId === "string")
|
|
1610
|
-
metadata.environmentId = asked.environmentId;
|
|
1611
|
-
const detail = {
|
|
1612
|
-
method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
|
|
1613
|
-
permissions
|
|
1614
|
-
};
|
|
1615
|
-
return {
|
|
1616
|
-
detail,
|
|
1617
|
-
deltaFields: {
|
|
1618
|
-
...callId !== undefined && { callId },
|
|
1619
|
-
...typeof asked.reason === "string" && { prompt: asked.reason },
|
|
1620
|
-
input: safeJsonValue(metadata)
|
|
1621
|
-
}
|
|
1622
|
-
};
|
|
1623
|
-
}
|
|
1624
|
-
function parseCodexElicitationRequest(params) {
|
|
1625
|
-
const asked = CodexMcpElicitationParamsSchema.parse(params);
|
|
1626
|
-
const toolName = nonEmptyString(asked.serverName);
|
|
1627
|
-
const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
|
|
1628
|
-
const metadata = {
|
|
1629
|
-
serverName: asked.serverName,
|
|
1630
|
-
threadId: asked.threadId,
|
|
1631
|
-
mode: asked.mode,
|
|
1632
|
-
message: asked.message
|
|
1633
|
-
};
|
|
1634
|
-
if (asked.turnId !== undefined)
|
|
1635
|
-
metadata.turnId = asked.turnId;
|
|
1636
|
-
if (asked.environmentId !== undefined)
|
|
1637
|
-
metadata.environmentId = asked.environmentId;
|
|
1638
|
-
if (asked._meta !== undefined)
|
|
1639
|
-
metadata._meta = asked._meta;
|
|
1640
|
-
if (asked.mode === "url") {
|
|
1641
|
-
metadata.elicitationId = asked.elicitationId;
|
|
1642
|
-
metadata.url = asked.url;
|
|
1643
|
-
} else {
|
|
1644
|
-
metadata.requestedSchema = asked.requestedSchema;
|
|
1645
|
-
}
|
|
1646
|
-
const detail = {
|
|
1647
|
-
method: CODEX_ELICITATION_REQUEST,
|
|
1648
|
-
elicitationMode: asked.mode
|
|
1649
|
-
};
|
|
1650
|
-
return {
|
|
1651
|
-
detail,
|
|
1652
|
-
deltaFields: {
|
|
1653
|
-
...callId !== undefined && { callId },
|
|
1654
|
-
...toolName !== undefined && { toolName },
|
|
1655
|
-
prompt: asked.message,
|
|
1656
|
-
input: safeJsonValue(metadata)
|
|
1657
|
-
}
|
|
1658
|
-
};
|
|
1659
|
-
}
|
|
1660
|
-
function parseCodexServerRequest(method, params) {
|
|
1661
|
-
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
1662
|
-
return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
|
|
1663
|
-
}
|
|
1664
|
-
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
1665
|
-
return { kind: "approval", ...parseCodexPermissionsRequest(params) };
|
|
1666
|
-
}
|
|
1667
|
-
if (method === CODEX_ELICITATION_REQUEST) {
|
|
1668
|
-
return { kind: "input", ...parseCodexElicitationRequest(params) };
|
|
1669
|
-
}
|
|
1670
|
-
return { kind: "input", ...parseCodexInputRequest(params) };
|
|
1671
|
-
}
|
|
1672
|
-
function codexStoppedAnswer(method) {
|
|
1673
|
-
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
1674
|
-
return { decision: CODEX_APPROVAL_DECISION.interrupted };
|
|
1675
|
-
}
|
|
1676
|
-
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
1677
|
-
return { permissions: {} };
|
|
1678
|
-
}
|
|
1679
|
-
if (method === CODEX_ELICITATION_REQUEST) {
|
|
1680
|
-
return { action: "cancel" };
|
|
1681
|
-
}
|
|
1682
|
-
return { answers: {} };
|
|
1683
|
-
}
|
|
1684
|
-
var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
|
|
1685
|
-
function buildCodexRequestAnswer(detail, rawReply) {
|
|
1686
|
-
const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
|
|
1687
|
-
if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
|
|
1688
|
-
if (reply.kind === "input") {
|
|
1689
|
-
throw new TypeError("A Codex approval is approved or denied, not answered with input");
|
|
1690
|
-
}
|
|
1691
|
-
if (reply.kind === "approve" && reply.updatedInput !== undefined) {
|
|
1692
|
-
throw new TypeError("Codex approval requests do not support updatedInput");
|
|
1693
|
-
}
|
|
1694
|
-
const decision = reply.kind === "approve" ? reply.scope === "session" ? CODEX_APPROVAL_DECISION.approveForSession : CODEX_APPROVAL_DECISION.approve : reply.interrupt === true ? CODEX_APPROVAL_DECISION.interrupted : CODEX_APPROVAL_DECISION.deny;
|
|
1695
|
-
if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
|
|
1696
|
-
throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
|
|
1697
|
-
}
|
|
1698
|
-
if (detail.availableDecisions !== undefined) {
|
|
1699
|
-
const allowed = detail.availableDecisions.some((entry) => entry === decision);
|
|
1700
|
-
if (!allowed) {
|
|
1701
|
-
throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
|
|
1702
|
-
}
|
|
1703
|
-
}
|
|
1704
|
-
return { decision };
|
|
1705
|
-
}
|
|
1706
|
-
if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
1707
|
-
if (reply.kind === "input") {
|
|
1708
|
-
throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
|
|
1709
|
-
}
|
|
1710
|
-
if (reply.kind === "approve") {
|
|
1711
|
-
if (reply.updatedInput !== undefined) {
|
|
1712
|
-
throw new TypeError("Codex permissions approval requests do not support updatedInput");
|
|
1713
|
-
}
|
|
1714
|
-
return {
|
|
1715
|
-
permissions: detail.permissions ?? {},
|
|
1716
|
-
scope: reply.scope === "session" ? "session" : "turn"
|
|
1717
|
-
};
|
|
1718
|
-
}
|
|
1719
|
-
if (reply.interrupt === true) {
|
|
1720
|
-
throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
|
|
1721
|
-
}
|
|
1722
|
-
return { permissions: {} };
|
|
1723
|
-
}
|
|
1724
|
-
if (detail.method === CODEX_ELICITATION_REQUEST) {
|
|
1725
|
-
if (reply.kind === "approve") {
|
|
1726
|
-
throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
|
|
1727
|
-
}
|
|
1728
|
-
if (reply.kind === "deny") {
|
|
1729
|
-
return {
|
|
1730
|
-
action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
1733
|
-
const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
|
|
1734
|
-
return {
|
|
1735
|
-
action: parsed.action,
|
|
1736
|
-
...parsed.content !== undefined && { content: parsed.content },
|
|
1737
|
-
...parsed._meta !== undefined && { _meta: parsed._meta }
|
|
1738
|
-
};
|
|
1739
|
-
}
|
|
1740
|
-
if (reply.kind !== "input") {
|
|
1741
|
-
throw new TypeError("A Codex input request is answered with input");
|
|
1742
|
-
}
|
|
1743
|
-
return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
|
|
1744
|
-
}
|
|
1745
|
-
function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
|
|
1746
|
-
const waiting = turn.pending.get(interactionId);
|
|
1747
|
-
if (waiting === undefined) {
|
|
1748
|
-
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
1749
|
-
}
|
|
1750
|
-
const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
|
|
1751
|
-
answerEngineRequest(turn, interactionId, answer);
|
|
1752
|
-
}
|
|
1753
|
-
function answerCodexSessionRequest(input) {
|
|
1754
|
-
if (input.turn?.pending.has(input.interactionId)) {
|
|
1755
|
-
answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
|
|
1756
|
-
return;
|
|
1757
|
-
}
|
|
1758
|
-
const external = input.externalPending.get(input.interactionId);
|
|
1759
|
-
if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
|
|
1760
|
-
throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
|
|
1761
|
-
}
|
|
1762
|
-
const answer = buildCodexRequestAnswer(external.detail, input.reply);
|
|
1763
|
-
input.externalPending.delete(input.interactionId);
|
|
1764
|
-
external.resolve(answer);
|
|
1765
|
-
}
|
|
1766
|
-
|
|
1767
|
-
// src/agent-executor/codex/turn-input.ts
|
|
1768
|
-
import { isAbsolute } from "node:path";
|
|
1769
|
-
import { z as z3 } from "zod";
|
|
1770
|
-
var NonEmptyNoNulStringSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00"), {
|
|
1771
|
-
message: "must be a non-empty string without NUL bytes"
|
|
1772
|
-
});
|
|
1773
|
-
var AbsolutePathNoNulSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00") && isAbsolute(value), {
|
|
1774
|
-
message: "must be an absolute path without NUL bytes"
|
|
1775
|
-
});
|
|
1776
|
-
var CodexSkillInputSchema = z3.strictObject({
|
|
1777
|
-
type: z3.literal("skill"),
|
|
1778
|
-
name: NonEmptyNoNulStringSchema,
|
|
1779
|
-
path: NonEmptyNoNulStringSchema
|
|
1780
|
-
});
|
|
1781
|
-
var CodexLocalImageInputSchema = z3.strictObject({
|
|
1782
|
-
type: z3.literal("localImage"),
|
|
1783
|
-
path: AbsolutePathNoNulSchema
|
|
1784
|
-
});
|
|
1785
|
-
function validateCodexExtraInput(part) {
|
|
1786
|
-
if (part.type === "skill") {
|
|
1787
|
-
const parsed = CodexSkillInputSchema.safeParse(part);
|
|
1788
|
-
if (!parsed.success) {
|
|
1789
|
-
throw new TypeError("Codex skill input name and path must be non-empty strings without NUL bytes");
|
|
1790
|
-
}
|
|
1791
|
-
return { type: "skill", name: parsed.data.name, path: parsed.data.path };
|
|
1792
|
-
}
|
|
1793
|
-
if (part.type === "localImage") {
|
|
1794
|
-
const parsed = CodexLocalImageInputSchema.safeParse(part);
|
|
1795
|
-
if (!parsed.success) {
|
|
1796
|
-
throw new TypeError("Codex localImage input path must be an absolute path without NUL bytes");
|
|
1797
|
-
}
|
|
1798
|
-
return { type: "localImage", path: parsed.data.path };
|
|
1799
|
-
}
|
|
1800
|
-
return;
|
|
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;
|
|
1801
1744
|
}
|
|
1802
1745
|
function inlineCodexParts(parts, options) {
|
|
1803
1746
|
return inlineOrderedParts(parts, {
|
|
@@ -1827,13 +1770,13 @@ function codexTurnInput(parts) {
|
|
|
1827
1770
|
}
|
|
1828
1771
|
return out;
|
|
1829
1772
|
}
|
|
1830
|
-
async function sendCodexTurnSteer(peer, params) {
|
|
1831
|
-
const steered = CodexTurnSteerResponseSchema
|
|
1773
|
+
async function sendCodexTurnSteer(peer, params, rpcOptions) {
|
|
1774
|
+
const steered = parseCodexResponse("turn/steer", CodexTurnSteerResponseSchema, await peer.request("turn/steer", {
|
|
1832
1775
|
threadId: params.threadId,
|
|
1833
1776
|
expectedTurnId: params.expectedTurnId,
|
|
1834
1777
|
input: codexTurnInput(params.parts),
|
|
1835
1778
|
...params.clientId !== undefined && { clientUserMessageId: params.clientId }
|
|
1836
|
-
}));
|
|
1779
|
+
}, rpcOptions));
|
|
1837
1780
|
return { turnId: steered.turnId };
|
|
1838
1781
|
}
|
|
1839
1782
|
|
|
@@ -1886,28 +1829,30 @@ function buildCodexThreadPolicyParams(base, overrides) {
|
|
|
1886
1829
|
params.config = safeJsonValue(merged.config);
|
|
1887
1830
|
return params;
|
|
1888
1831
|
}
|
|
1889
|
-
function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
|
|
1890
|
-
|
|
1832
|
+
function validateCodexTurnStartOverrides(caller, turnInput, activeModelProvider) {
|
|
1833
|
+
assertRequiredNonEmptyString(turnInput.clientId, "clientId", caller);
|
|
1834
|
+
assertOptionalNonEmptyNoNulString(turnInput.cwd, "cwd", caller);
|
|
1891
1835
|
if (turnInput.modelProvider !== undefined) {
|
|
1892
1836
|
if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
|
|
1893
1837
|
throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
|
|
1894
1838
|
}
|
|
1895
1839
|
}
|
|
1896
1840
|
if (turnInput.collaborationMode !== undefined) {
|
|
1897
|
-
|
|
1841
|
+
CodexCollaborationModeSchema2.parse(turnInput.collaborationMode);
|
|
1898
1842
|
}
|
|
1899
1843
|
if (turnInput.approvalPolicy !== undefined) {
|
|
1900
|
-
|
|
1844
|
+
CodexApprovalPolicySchema2.parse(turnInput.approvalPolicy);
|
|
1901
1845
|
}
|
|
1902
1846
|
if (turnInput.sandboxPolicy !== undefined) {
|
|
1847
|
+
CodexSandboxPolicySchema2.parse(turnInput.sandboxPolicy);
|
|
1903
1848
|
safeJsonValue(turnInput.sandboxPolicy);
|
|
1904
1849
|
}
|
|
1905
1850
|
if (turnInput.runtimeWorkspaceRoots !== undefined) {
|
|
1906
|
-
validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots },
|
|
1851
|
+
validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, caller);
|
|
1907
1852
|
}
|
|
1908
1853
|
}
|
|
1909
|
-
function
|
|
1910
|
-
validateCodexTurnStartOverrides(turnInput, activeModelProvider);
|
|
1854
|
+
function buildCodexTurnStartRpcParams(caller, threadId, turnInput, parts, activeModelProvider) {
|
|
1855
|
+
validateCodexTurnStartOverrides(caller, turnInput, activeModelProvider);
|
|
1911
1856
|
const params = {
|
|
1912
1857
|
threadId,
|
|
1913
1858
|
input: codexTurnInput(parts),
|
|
@@ -1920,7 +1865,7 @@ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvid
|
|
|
1920
1865
|
if (turnInput.reasoningEffort !== undefined)
|
|
1921
1866
|
params.effort = turnInput.reasoningEffort;
|
|
1922
1867
|
if (turnInput.collaborationMode !== undefined) {
|
|
1923
|
-
params.collaborationMode =
|
|
1868
|
+
params.collaborationMode = CodexCollaborationModeSchema2.parse(turnInput.collaborationMode);
|
|
1924
1869
|
}
|
|
1925
1870
|
if (turnInput.approvalPolicy !== undefined) {
|
|
1926
1871
|
params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
|
|
@@ -1935,26 +1880,28 @@ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvid
|
|
|
1935
1880
|
}
|
|
1936
1881
|
function createCodexSessionMutators(input) {
|
|
1937
1882
|
return {
|
|
1938
|
-
async steerTurn(steerInput) {
|
|
1883
|
+
async steerTurn(steerInput, rpcOptions) {
|
|
1939
1884
|
input.ensureAlive();
|
|
1885
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1940
1886
|
const caller = "CodexSession.steerTurn";
|
|
1941
1887
|
const targetThreadId = steerInput.threadId === undefined ? input.threadId : assertNonEmptyThreadId(steerInput.threadId, caller);
|
|
1942
1888
|
assertOptionalNonEmptyString(steerInput.clientId, "clientId", caller);
|
|
1943
1889
|
assertOptionalNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
|
|
1944
1890
|
if (targetThreadId !== input.threadId) {
|
|
1945
1891
|
const expectedTurnId = assertRequiredNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
|
|
1946
|
-
const parts = await inlineCodexParts(steerInput.input, {
|
|
1892
|
+
const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(steerInput.input, {
|
|
1947
1893
|
...input.imageOptions,
|
|
1948
1894
|
driverLabel: "The Codex driver",
|
|
1949
|
-
signal
|
|
1950
|
-
});
|
|
1895
|
+
signal
|
|
1896
|
+
}));
|
|
1951
1897
|
input.ensureAlive();
|
|
1898
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1952
1899
|
return sendCodexTurnSteer(input.peer, {
|
|
1953
1900
|
threadId: targetThreadId,
|
|
1954
1901
|
expectedTurnId,
|
|
1955
1902
|
parts,
|
|
1956
1903
|
...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
|
|
1957
|
-
});
|
|
1904
|
+
}, rpcOptions);
|
|
1958
1905
|
}
|
|
1959
1906
|
const active = input.getActiveTurn();
|
|
1960
1907
|
let expectedTurnId;
|
|
@@ -1972,12 +1919,13 @@ function createCodexSessionMutators(input) {
|
|
|
1972
1919
|
}
|
|
1973
1920
|
expectedTurnId = steerInput.expectedTurnId;
|
|
1974
1921
|
}
|
|
1975
|
-
const parts = await inlineCodexParts(steerInput.input, {
|
|
1922
|
+
const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(steerInput.input, {
|
|
1976
1923
|
...input.imageOptions,
|
|
1977
1924
|
driverLabel: "The Codex driver",
|
|
1978
|
-
signal
|
|
1979
|
-
});
|
|
1925
|
+
signal
|
|
1926
|
+
}));
|
|
1980
1927
|
input.ensureAlive();
|
|
1928
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1981
1929
|
const afterAwait = input.getActiveTurn();
|
|
1982
1930
|
if (active !== undefined) {
|
|
1983
1931
|
if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
|
|
@@ -1991,13 +1939,14 @@ function createCodexSessionMutators(input) {
|
|
|
1991
1939
|
expectedTurnId,
|
|
1992
1940
|
parts,
|
|
1993
1941
|
...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
|
|
1994
|
-
});
|
|
1942
|
+
}, rpcOptions);
|
|
1995
1943
|
},
|
|
1996
|
-
async forkThread(options = {}) {
|
|
1944
|
+
async forkThread(options = {}, rpcOptions) {
|
|
1997
1945
|
input.ensureAlive();
|
|
1946
|
+
validateCodexRpcCallOptions(rpcOptions);
|
|
1998
1947
|
validateCodexForkBounds(options, "CodexSession.forkThread");
|
|
1999
1948
|
const policyParams = buildCodexThreadPolicyParams({}, options);
|
|
2000
|
-
const forked = CodexStartedThreadSchema
|
|
1949
|
+
const forked = parseCodexResponse("thread/fork", CodexStartedThreadSchema, await input.peer.request("thread/fork", {
|
|
2001
1950
|
threadId: input.threadId,
|
|
2002
1951
|
...policyParams,
|
|
2003
1952
|
...options.cwd !== undefined && { cwd: options.cwd },
|
|
@@ -2007,7 +1956,7 @@ function createCodexSessionMutators(input) {
|
|
|
2007
1956
|
...options.deferGoalContinuation !== undefined && {
|
|
2008
1957
|
deferGoalContinuation: options.deferGoalContinuation
|
|
2009
1958
|
}
|
|
2010
|
-
}));
|
|
1959
|
+
}, rpcOptions));
|
|
2011
1960
|
return {
|
|
2012
1961
|
nativeThreadId: forked.thread.id,
|
|
2013
1962
|
threadContext: extractCodexThreadContext(forked)
|
|
@@ -2016,671 +1965,735 @@ function createCodexSessionMutators(input) {
|
|
|
2016
1965
|
};
|
|
2017
1966
|
}
|
|
2018
1967
|
|
|
2019
|
-
// src/agent-executor/codex/
|
|
2020
|
-
function
|
|
2021
|
-
|
|
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))
|
|
2022
1974
|
return;
|
|
2023
|
-
|
|
2024
|
-
drainEngineRequests(turn, codexStopped);
|
|
1975
|
+
return field(params, "threadId") ?? field(params.thread, "id") ?? field(params.turn, "threadId") ?? field(params.item, "threadId");
|
|
2025
1976
|
}
|
|
2026
|
-
function
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
if (params.excludeTurns !== undefined && typeof params.excludeTurns !== "boolean") {
|
|
2031
|
-
throw new TypeError(`[stitchkit] ${caller}: excludeTurns must be a boolean`);
|
|
2032
|
-
}
|
|
2033
|
-
const policyParams = buildCodexThreadPolicyParams({}, params);
|
|
2034
|
-
return {
|
|
2035
|
-
threadId,
|
|
2036
|
-
excludeTurns: params.excludeTurns ?? true,
|
|
2037
|
-
...policyParams,
|
|
2038
|
-
...params.cwd !== undefined && { cwd: params.cwd }
|
|
2039
|
-
};
|
|
1977
|
+
function codexTurnIdOf(params) {
|
|
1978
|
+
if (!isRecord(params))
|
|
1979
|
+
return;
|
|
1980
|
+
return field(params, "turnId") ?? field(params.turn, "id") ?? field(params.item, "turnId");
|
|
2040
1981
|
}
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
}
|
|
2074
|
-
return {
|
|
2075
|
-
nativeTurnId,
|
|
2076
|
-
deltas: turn.channel,
|
|
2077
|
-
async interrupt() {
|
|
2078
|
-
interruptLocalCodexTurn(turn, nativeTurnId);
|
|
2079
|
-
await input.peer.request("turn/interrupt", {
|
|
2080
|
-
threadId: input.threadId,
|
|
2081
|
-
turnId: nativeTurnId
|
|
2082
|
-
});
|
|
2083
|
-
},
|
|
2084
|
-
async respond(interactionId, rawReply) {
|
|
2085
|
-
answerActiveCodexTurnRequest(turn, interactionId, rawReply);
|
|
2086
|
-
}
|
|
2087
|
-
};
|
|
2088
|
-
}
|
|
2089
|
-
});
|
|
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;
|
|
2090
2014
|
}
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2015
|
+
|
|
2016
|
+
// src/agent-executor/codex/request-answers.ts
|
|
2017
|
+
function isKnownCodexRequestMethod(method) {
|
|
2018
|
+
return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
|
|
2019
|
+
}
|
|
2020
|
+
function parseCodexApprovalRequest(method, params) {
|
|
2021
|
+
const asked = CodexApprovalParamsSchema.parse(params);
|
|
2022
|
+
const callId = nonEmptyString(asked.itemId);
|
|
2023
|
+
const metadata = {};
|
|
2024
|
+
if (typeof asked.command === "string")
|
|
2025
|
+
metadata.command = asked.command;
|
|
2026
|
+
if (typeof asked.cwd === "string")
|
|
2027
|
+
metadata.cwd = asked.cwd;
|
|
2028
|
+
if (typeof asked.reason === "string")
|
|
2029
|
+
metadata.reason = asked.reason;
|
|
2030
|
+
if (typeof asked.grantRoot === "string")
|
|
2031
|
+
metadata.grantRoot = asked.grantRoot;
|
|
2032
|
+
if (typeof asked.kind === "string")
|
|
2033
|
+
metadata.kind = asked.kind;
|
|
2034
|
+
if (typeof asked.approvalId === "string")
|
|
2035
|
+
metadata.approvalId = asked.approvalId;
|
|
2036
|
+
if (asked.commandActions != null)
|
|
2037
|
+
metadata.commandActions = asked.commandActions;
|
|
2038
|
+
if (asked.availableDecisions != null)
|
|
2039
|
+
metadata.availableDecisions = asked.availableDecisions;
|
|
2040
|
+
const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
|
|
2041
|
+
const detail = {
|
|
2042
|
+
method,
|
|
2043
|
+
...typeof asked.kind === "string" && { kind: asked.kind },
|
|
2044
|
+
...Array.isArray(asked.availableDecisions) && {
|
|
2045
|
+
availableDecisions: asked.availableDecisions
|
|
2098
2046
|
}
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2047
|
+
};
|
|
2048
|
+
return {
|
|
2049
|
+
detail,
|
|
2050
|
+
deltaFields: {
|
|
2051
|
+
...callId !== undefined && { callId },
|
|
2052
|
+
...typeof asked.command === "string" && { prompt: asked.command },
|
|
2053
|
+
...input !== undefined && { input }
|
|
2054
|
+
}
|
|
2055
|
+
};
|
|
2102
2056
|
}
|
|
2103
|
-
function
|
|
2104
|
-
const
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
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
|
+
}))
|
|
2114
2069
|
},
|
|
2115
|
-
...
|
|
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
|
+
}
|
|
2116
2080
|
};
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
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
|
+
}
|
|
2134
2108
|
};
|
|
2135
|
-
return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
|
|
2136
2109
|
}
|
|
2137
|
-
function
|
|
2138
|
-
const
|
|
2139
|
-
|
|
2140
|
-
|
|
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
|
|
2141
2119
|
};
|
|
2142
|
-
if (
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
});
|
|
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;
|
|
2154
2131
|
}
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
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) };
|
|
2161
2149
|
}
|
|
2162
|
-
|
|
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) };
|
|
2163
2157
|
}
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
if (cursor === undefined || cursor === null)
|
|
2168
|
-
return;
|
|
2169
|
-
if (typeof cursor === "string") {
|
|
2170
|
-
if (cursor.trim().length === 0) {
|
|
2171
|
-
throw new TypeError(`[stitchkit] ${caller}: cursor must be a non-empty string`);
|
|
2172
|
-
}
|
|
2173
|
-
return;
|
|
2158
|
+
function codexStoppedAnswer(method) {
|
|
2159
|
+
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
2160
|
+
return { decision: CODEX_APPROVAL_DECISION.interrupted };
|
|
2174
2161
|
}
|
|
2175
|
-
if (
|
|
2176
|
-
|
|
2162
|
+
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
2163
|
+
return { permissions: {} };
|
|
2164
|
+
}
|
|
2165
|
+
if (method === CODEX_ELICITATION_REQUEST) {
|
|
2166
|
+
return { action: "cancel" };
|
|
2177
2167
|
}
|
|
2168
|
+
return { answers: {} };
|
|
2178
2169
|
}
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
},
|
|
2198
|
-
listCollaborationModes() {
|
|
2199
|
-
return call("collaborationMode/list", {});
|
|
2200
|
-
},
|
|
2201
|
-
async listTurns(params) {
|
|
2202
|
-
const caller = "CodexControlClient.listTurns";
|
|
2203
|
-
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2204
|
-
assertOptionalLimit(params.limit, caller);
|
|
2205
|
-
if (params.cursor !== undefined && params.cursor !== null && typeof params.cursor !== "string") {
|
|
2206
|
-
throw new TypeError(`[stitchkit] ${caller}: cursor must be a string or null`);
|
|
2207
|
-
}
|
|
2208
|
-
return call("thread/turns/list", {
|
|
2209
|
-
threadId,
|
|
2210
|
-
...params.cursor !== undefined && { cursor: params.cursor },
|
|
2211
|
-
...params.limit !== undefined && { limit: params.limit },
|
|
2212
|
-
...params.itemsView !== undefined && { itemsView: params.itemsView },
|
|
2213
|
-
...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
|
|
2214
|
-
});
|
|
2215
|
-
},
|
|
2216
|
-
async listItems(params) {
|
|
2217
|
-
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listItems");
|
|
2218
|
-
assertOptionalLimit(params.limit, "CodexControlClient.listItems");
|
|
2219
|
-
assertOptionalNonEmptyString(params.turnId, "turnId", "CodexControlClient.listItems");
|
|
2220
|
-
assertOptionalItemsCursor(params.cursor, "CodexControlClient.listItems");
|
|
2221
|
-
return call("thread/items/list", {
|
|
2222
|
-
threadId,
|
|
2223
|
-
...params.turnId !== undefined && { turnId: params.turnId },
|
|
2224
|
-
...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
|
|
2225
|
-
...params.limit !== undefined && { limit: params.limit },
|
|
2226
|
-
...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
|
|
2227
|
-
...params.deferOutput !== undefined && {
|
|
2228
|
-
deferOutput: safeJsonValue(params.deferOutput)
|
|
2229
|
-
}
|
|
2230
|
-
});
|
|
2231
|
-
},
|
|
2232
|
-
listMcpServerStatus(params) {
|
|
2233
|
-
return call("mcpServerStatus/list", {
|
|
2234
|
-
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
2235
|
-
...params?.limit !== undefined && { limit: params.limit },
|
|
2236
|
-
...params?.threadId !== undefined && { threadId: params.threadId },
|
|
2237
|
-
...params?.serverName !== undefined && { serverName: params.serverName },
|
|
2238
|
-
...params?.detail !== undefined && { detail: params.detail }
|
|
2239
|
-
});
|
|
2240
|
-
},
|
|
2241
|
-
listSkills(params) {
|
|
2242
|
-
return call("skills/list", {
|
|
2243
|
-
...params?.cwds !== undefined && { cwds: [...params.cwds] },
|
|
2244
|
-
...params?.forceReload !== undefined && { forceReload: params.forceReload }
|
|
2245
|
-
});
|
|
2246
|
-
},
|
|
2247
|
-
listModels(params) {
|
|
2248
|
-
return call("model/list", {
|
|
2249
|
-
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
2250
|
-
...params?.limit !== undefined && { limit: params.limit },
|
|
2251
|
-
...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
|
|
2252
|
-
...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
|
|
2253
|
-
});
|
|
2254
|
-
},
|
|
2255
|
-
readAccount(params) {
|
|
2256
|
-
return call("account/read", {
|
|
2257
|
-
...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
|
|
2258
|
-
});
|
|
2259
|
-
},
|
|
2260
|
-
readRateLimits() {
|
|
2261
|
-
return call("account/rateLimits/read");
|
|
2262
|
-
},
|
|
2263
|
-
async resumeThread(params) {
|
|
2264
|
-
input.ensureAlive();
|
|
2265
|
-
return call("thread/resume", buildCodexResumeThreadParams(params));
|
|
2266
|
-
},
|
|
2267
|
-
async steerTurn(params) {
|
|
2268
|
-
input.ensureAlive();
|
|
2269
|
-
const caller = "CodexControlClient.steerTurn";
|
|
2270
|
-
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2271
|
-
const expectedTurnId = assertRequiredNonEmptyString(params.expectedTurnId, "expectedTurnId", caller);
|
|
2272
|
-
assertOptionalNonEmptyString(params.clientId, "clientId", caller);
|
|
2273
|
-
const parts = await inlineCodexParts(params.input, {
|
|
2274
|
-
...input.imageOptions,
|
|
2275
|
-
driverLabel: "The Codex driver",
|
|
2276
|
-
signal: input.signal
|
|
2277
|
-
});
|
|
2278
|
-
input.ensureAlive();
|
|
2279
|
-
return sendCodexTurnSteer(input.peer, {
|
|
2280
|
-
threadId,
|
|
2281
|
-
expectedTurnId,
|
|
2282
|
-
parts,
|
|
2283
|
-
...params.clientId !== undefined && { clientId: params.clientId }
|
|
2284
|
-
});
|
|
2285
|
-
},
|
|
2286
|
-
...createCodexThreadControlMethods(call, {
|
|
2287
|
-
ensureAlive: input.ensureAlive,
|
|
2288
|
-
...input.onBeforeInterruptTurn !== undefined && {
|
|
2289
|
-
onBeforeInterruptTurn: input.onBeforeInterruptTurn
|
|
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)}`);
|
|
2290
2188
|
}
|
|
2291
|
-
})
|
|
2292
|
-
};
|
|
2293
|
-
}
|
|
2294
|
-
function bindCodexSessionThreadControls(controlClient, threadId) {
|
|
2295
|
-
return {
|
|
2296
|
-
readThread(params) {
|
|
2297
|
-
return controlClient.readThread({
|
|
2298
|
-
...params,
|
|
2299
|
-
threadId: params?.threadId ?? threadId
|
|
2300
|
-
});
|
|
2301
|
-
},
|
|
2302
|
-
listTurns(params) {
|
|
2303
|
-
return controlClient.listTurns({
|
|
2304
|
-
...params,
|
|
2305
|
-
threadId: params?.threadId ?? threadId
|
|
2306
|
-
});
|
|
2307
|
-
},
|
|
2308
|
-
listItems(params) {
|
|
2309
|
-
return controlClient.listItems({
|
|
2310
|
-
...params,
|
|
2311
|
-
threadId: params?.threadId ?? threadId
|
|
2312
|
-
});
|
|
2313
|
-
},
|
|
2314
|
-
resumeThread(params) {
|
|
2315
|
-
return controlClient.resumeThread({
|
|
2316
|
-
...params,
|
|
2317
|
-
threadId: params?.threadId ?? threadId
|
|
2318
|
-
});
|
|
2319
|
-
},
|
|
2320
|
-
revertThread(params) {
|
|
2321
|
-
return controlClient.revertThread({
|
|
2322
|
-
...params,
|
|
2323
|
-
threadId: params.threadId ?? threadId
|
|
2324
|
-
});
|
|
2325
|
-
},
|
|
2326
|
-
injectItems(params) {
|
|
2327
|
-
return controlClient.injectItems({
|
|
2328
|
-
...params,
|
|
2329
|
-
threadId: params.threadId ?? threadId
|
|
2330
|
-
});
|
|
2331
|
-
},
|
|
2332
|
-
unsubscribeThread(params) {
|
|
2333
|
-
return controlClient.unsubscribeThread({
|
|
2334
|
-
threadId: params?.threadId ?? threadId
|
|
2335
|
-
});
|
|
2336
|
-
},
|
|
2337
|
-
archiveThread(params) {
|
|
2338
|
-
return controlClient.archiveThread({
|
|
2339
|
-
threadId: params?.threadId ?? threadId
|
|
2340
|
-
});
|
|
2341
|
-
},
|
|
2342
|
-
unarchiveThread(params) {
|
|
2343
|
-
return controlClient.unarchiveThread({
|
|
2344
|
-
threadId: params?.threadId ?? threadId
|
|
2345
|
-
});
|
|
2346
|
-
},
|
|
2347
|
-
updateThreadMetadata(params) {
|
|
2348
|
-
return controlClient.updateThreadMetadata({
|
|
2349
|
-
...params,
|
|
2350
|
-
threadId: params?.threadId ?? threadId
|
|
2351
|
-
});
|
|
2352
|
-
},
|
|
2353
|
-
setThreadName(params) {
|
|
2354
|
-
return controlClient.setThreadName({
|
|
2355
|
-
...params,
|
|
2356
|
-
threadId: params.threadId ?? threadId
|
|
2357
|
-
});
|
|
2358
|
-
},
|
|
2359
|
-
interruptTurn(params) {
|
|
2360
|
-
return controlClient.interruptTurn({
|
|
2361
|
-
...params,
|
|
2362
|
-
threadId: params.threadId ?? threadId
|
|
2363
|
-
});
|
|
2364
|
-
},
|
|
2365
|
-
compactThread(params) {
|
|
2366
|
-
return controlClient.compactThread({
|
|
2367
|
-
threadId: params?.threadId ?? threadId
|
|
2368
|
-
});
|
|
2369
2189
|
}
|
|
2370
|
-
|
|
2371
|
-
}
|
|
2372
|
-
|
|
2373
|
-
// src/agent-executor/codex/classify.ts
|
|
2374
|
-
var raw = (type) => ({ source: "codex", type });
|
|
2375
|
-
var CODEX_TOOL_ITEMS = new Set([
|
|
2376
|
-
"commandExecution",
|
|
2377
|
-
"fileChange",
|
|
2378
|
-
"mcpToolCall",
|
|
2379
|
-
"dynamicToolCall",
|
|
2380
|
-
"collabAgentToolCall",
|
|
2381
|
-
"webSearch",
|
|
2382
|
-
"imageView",
|
|
2383
|
-
"sleep",
|
|
2384
|
-
"imageGeneration",
|
|
2385
|
-
"functionCallOutput"
|
|
2386
|
-
]);
|
|
2387
|
-
var STATUSLESS_TOOL_ITEMS = new Set([
|
|
2388
|
-
"webSearch",
|
|
2389
|
-
"imageView",
|
|
2390
|
-
"sleep",
|
|
2391
|
-
"functionCallOutput"
|
|
2392
|
-
]);
|
|
2393
|
-
var CODEX_CONTENT_ITEMS = new Set([
|
|
2394
|
-
"agentMessage",
|
|
2395
|
-
"reasoning",
|
|
2396
|
-
"userMessage",
|
|
2397
|
-
"plan",
|
|
2398
|
-
"contextCompaction",
|
|
2399
|
-
"hookPrompt",
|
|
2400
|
-
"subAgentActivity",
|
|
2401
|
-
"enteredReviewMode",
|
|
2402
|
-
"exitedReviewMode"
|
|
2403
|
-
]);
|
|
2404
|
-
var KNOWN_CODEX_ERROR_CODES = new Set([
|
|
2405
|
-
"contextWindowExceeded",
|
|
2406
|
-
"sessionBudgetExceeded",
|
|
2407
|
-
"usageLimitExceeded",
|
|
2408
|
-
"rateLimitExceeded",
|
|
2409
|
-
"flexUnavailable",
|
|
2410
|
-
"serverOverloaded",
|
|
2411
|
-
"modelNotFound",
|
|
2412
|
-
"policyCapacityUnavailable",
|
|
2413
|
-
"cyberPolicy",
|
|
2414
|
-
"bioPolicy",
|
|
2415
|
-
"misalignmentPolicyViolation",
|
|
2416
|
-
"tooManyDenials",
|
|
2417
|
-
"internalServerError",
|
|
2418
|
-
"unauthorized",
|
|
2419
|
-
"badRequest",
|
|
2420
|
-
"threadRollbackFailed",
|
|
2421
|
-
"sandboxError",
|
|
2422
|
-
"other",
|
|
2423
|
-
"inferenceHookDenied"
|
|
2424
|
-
]);
|
|
2425
|
-
var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
|
|
2426
|
-
"httpConnectionFailed",
|
|
2427
|
-
"responseStreamConnectionFailed",
|
|
2428
|
-
"responseStreamDisconnected",
|
|
2429
|
-
"responseTooManyFailedAttempts",
|
|
2430
|
-
"activeTurnNotSteerable"
|
|
2431
|
-
]);
|
|
2432
|
-
var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
|
|
2433
|
-
function toolName(item) {
|
|
2434
|
-
if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
|
|
2435
|
-
return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
|
|
2436
|
-
}
|
|
2437
|
-
if (item.type === "functionCallOutput") {
|
|
2438
|
-
return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
|
|
2439
|
-
}
|
|
2440
|
-
return item.type;
|
|
2441
|
-
}
|
|
2442
|
-
function toolInput(item) {
|
|
2443
|
-
const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
|
|
2444
|
-
return safeJsonValue(rest);
|
|
2445
|
-
}
|
|
2446
|
-
function isKnownCodexErrorInfo(info) {
|
|
2447
|
-
if (typeof info === "string")
|
|
2448
|
-
return KNOWN_CODEX_ERROR_CODES.has(info);
|
|
2449
|
-
if (typeof info === "object" && info !== null && !Array.isArray(info)) {
|
|
2450
|
-
const keys = Object.keys(info);
|
|
2451
|
-
return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
|
|
2190
|
+
return { decision };
|
|
2452
2191
|
}
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
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: {} };
|
|
2461
2209
|
}
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
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");
|
|
2469
2228
|
}
|
|
2229
|
+
return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
|
|
2470
2230
|
}
|
|
2471
|
-
function
|
|
2472
|
-
const
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
if (rawMessage.length > 0) {
|
|
2476
|
-
if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
|
|
2477
|
-
return `${rawMessage} (${infoSummary})`;
|
|
2478
|
-
}
|
|
2479
|
-
return rawMessage;
|
|
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`);
|
|
2480
2235
|
}
|
|
2481
|
-
|
|
2482
|
-
|
|
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;
|
|
2483
2243
|
}
|
|
2484
|
-
|
|
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);
|
|
2485
2251
|
}
|
|
2486
|
-
|
|
2487
|
-
|
|
2252
|
+
|
|
2253
|
+
// src/agent-executor/codex/thread-open.ts
|
|
2254
|
+
function interruptLocalCodexTurn(turn, turnId) {
|
|
2255
|
+
if (turn === undefined || turn.codexTurnId !== turnId)
|
|
2488
2256
|
return;
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
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`);
|
|
2496
2266
|
}
|
|
2497
|
-
|
|
2267
|
+
const policyParams = buildCodexThreadPolicyParams({}, params);
|
|
2268
|
+
return {
|
|
2269
|
+
threadId,
|
|
2270
|
+
excludeTurns: params.excludeTurns ?? true,
|
|
2271
|
+
...policyParams,
|
|
2272
|
+
...params.cwd !== undefined && { cwd: params.cwd }
|
|
2273
|
+
};
|
|
2498
2274
|
}
|
|
2499
|
-
function
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
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
|
+
});
|
|
2510
2333
|
}
|
|
2511
|
-
function
|
|
2512
|
-
if (
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
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");
|
|
2341
|
+
}
|
|
2342
|
+
validateCodexForkBounds(input.forkFrom, "CodexDriver.open");
|
|
2343
|
+
validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
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
|
|
2519
2354
|
},
|
|
2520
|
-
...
|
|
2521
|
-
|
|
2355
|
+
...config.runtimeWorkspaceRoots !== undefined && {
|
|
2356
|
+
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
2522
2357
|
},
|
|
2523
|
-
...
|
|
2524
|
-
|
|
2358
|
+
...config.config !== undefined && { config: config.config }
|
|
2359
|
+
};
|
|
2360
|
+
const withFork = forkFrom === undefined ? basePolicy : {
|
|
2361
|
+
...basePolicy,
|
|
2362
|
+
...forkFrom.model !== undefined && { model: forkFrom.model },
|
|
2363
|
+
...forkFrom.modelProvider !== undefined && {
|
|
2364
|
+
modelProvider: forkFrom.modelProvider
|
|
2525
2365
|
},
|
|
2526
|
-
...
|
|
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 ?? {} } } : {}
|
|
2527
2377
|
};
|
|
2528
|
-
return
|
|
2378
|
+
return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
|
|
2529
2379
|
}
|
|
2530
|
-
function
|
|
2531
|
-
const
|
|
2532
|
-
|
|
2380
|
+
function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
|
|
2381
|
+
const threadParams = {
|
|
2382
|
+
cwd: input.cwd,
|
|
2383
|
+
...mergeOpenThreadPolicy(config, input.forkFrom, dynamicOverrides)
|
|
2384
|
+
};
|
|
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
|
+
});
|
|
2397
|
+
}
|
|
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);
|
|
2414
|
+
};
|
|
2533
2415
|
return {
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
...
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
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
|
|
2554
2463
|
}
|
|
2555
|
-
|
|
2464
|
+
})
|
|
2556
2465
|
};
|
|
2557
2466
|
}
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
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;
|
|
2494
|
+
}
|
|
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);
|
|
2502
|
+
}
|
|
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;
|
|
2517
|
+
}
|
|
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 mergeBucket(windows, bucket, 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 sharedDuration = primary?.mins !== undefined && primary.mins === secondary?.mins;
|
|
2527
|
+
const slots = { primary, secondary };
|
|
2528
|
+
for (const slot of ["primary", "secondary"]) {
|
|
2529
|
+
const measurement = slots[slot];
|
|
2530
|
+
if (!measurement)
|
|
2531
|
+
continue;
|
|
2532
|
+
const sameDuration = (w) => w.bucket === bucket && w.mins === measurement.mins;
|
|
2533
|
+
let previous = windows.findIndex((w) => sameDuration(w) && w.slot === slot);
|
|
2534
|
+
if (previous < 0 && measurement.mins !== undefined && !sharedDuration) {
|
|
2535
|
+
previous = windows.findIndex(sameDuration);
|
|
2567
2536
|
}
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2537
|
+
const window = { ...measurement, bucket, slot, label };
|
|
2538
|
+
if (previous >= 0)
|
|
2539
|
+
windows[previous] = window;
|
|
2540
|
+
else if (windows.length < MAX_PLAN_WINDOWS)
|
|
2541
|
+
windows.push(window);
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
function nameBucketWindows(windows) {
|
|
2545
|
+
const seen = new Set;
|
|
2546
|
+
return windows.map((window) => {
|
|
2547
|
+
const { bucket, slot, usedPercent, mins, resetsAt, label } = window;
|
|
2548
|
+
const sharedDuration = mins !== undefined && windows.some((other) => other !== window && other.bucket === bucket && other.mins === mins);
|
|
2549
|
+
const suffix = mins === undefined ? `:${slot}` : sharedDuration ? `:${mins}m:${slot}` : `:${mins}m`;
|
|
2550
|
+
const name = clampUniqueWindowName(bucket, suffix, seen, `${bucket}:${slot}`, MAX_WINDOW_NAME_CHARS);
|
|
2551
|
+
return PlanWindowSchema2.parse({
|
|
2552
|
+
name,
|
|
2553
|
+
usedPercent: Math.min(100, usedPercent),
|
|
2554
|
+
...resetsAt !== undefined && { resetsAt },
|
|
2555
|
+
...mins !== undefined && { windowDurationMins: mins },
|
|
2556
|
+
...label !== undefined && { label }
|
|
2557
|
+
});
|
|
2558
|
+
});
|
|
2559
|
+
}
|
|
2560
|
+
function parseCodexRateLimitsInternal(reported) {
|
|
2561
|
+
if (!isRecord(reported))
|
|
2562
|
+
return { windows: [], plan: undefined };
|
|
2563
|
+
const windows = [];
|
|
2564
|
+
let plan;
|
|
2565
|
+
function readBucket(raw, fallbackId) {
|
|
2566
|
+
const parsed = SnapshotSchema.safeParse(raw);
|
|
2567
|
+
if (!parsed.success)
|
|
2568
|
+
return fallbackId;
|
|
2569
|
+
const snapshot = parsed.data;
|
|
2570
|
+
plan ??= clampPlanName(snapshot.planType ?? snapshot.plan_type, MAX_WINDOW_NAME_CHARS);
|
|
2571
|
+
const id = nonEmptyString(snapshot.limitId ?? snapshot.limit_id)?.trim() ?? fallbackId;
|
|
2572
|
+
mergeBucket(windows, id, snapshot);
|
|
2573
|
+
return id;
|
|
2574
|
+
}
|
|
2575
|
+
const byId = reported.rateLimitsByLimitId ?? reported.rate_limits_by_limit_id;
|
|
2576
|
+
const defaultId = isRecord(byId) && isRecord(byId.codex) ? "codex" : "limit";
|
|
2577
|
+
const accountId = readBucket(reported.rateLimits ?? reported.rate_limits ?? reported, defaultId);
|
|
2578
|
+
if (isRecord(byId)) {
|
|
2579
|
+
if (Object.hasOwn(byId, accountId))
|
|
2580
|
+
readBucket(byId[accountId], accountId);
|
|
2581
|
+
for (const key of Object.keys(byId).sort((a, b) => a.localeCompare(b))) {
|
|
2582
|
+
if (windows.length >= MAX_PLAN_WINDOWS)
|
|
2583
|
+
break;
|
|
2584
|
+
if (key !== accountId)
|
|
2585
|
+
readBucket(byId[key], nonEmptyString(key)?.trim() ?? "limit");
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
return { windows: nameBucketWindows(windows), plan };
|
|
2589
|
+
}
|
|
2590
|
+
function codexPlanWindows(reported) {
|
|
2591
|
+
return parseCodexRateLimitsInternal(reported).windows;
|
|
2592
|
+
}
|
|
2593
|
+
function codexPlanLimits(reported, now = new Date) {
|
|
2594
|
+
const { windows, plan } = parseCodexRateLimitsInternal(reported);
|
|
2595
|
+
return PlanLimitsSchema2.parse({
|
|
2596
|
+
answer: windows.length > 0 ? "known" : "unpublished",
|
|
2597
|
+
windows,
|
|
2598
|
+
observedAt: now.toISOString(),
|
|
2599
|
+
...plan !== undefined && { plan }
|
|
2600
|
+
});
|
|
2601
|
+
}
|
|
2602
|
+
|
|
2603
|
+
// src/agent-executor/codex/pagination.ts
|
|
2604
|
+
var DEFAULT_FIND_TURN_MAX_PAGES = 256;
|
|
2605
|
+
var DEFAULT_FIND_TURN_PAGE_SIZE = 50;
|
|
2606
|
+
var MAX_UINT322 = 4294967295;
|
|
2607
|
+
async function walkCodexPages(fetchPage, options, onPage, repeatedCursorLabel) {
|
|
2608
|
+
assertPositiveSafeInteger("maxPages", options.maxPages, TypeError, { absent: "refused" });
|
|
2609
|
+
const onRepeatedCursor = options.onRepeatedCursor ?? "throw";
|
|
2610
|
+
if (onRepeatedCursor !== "throw" && onRepeatedCursor !== "stop") {
|
|
2611
|
+
throw new TypeError(`[stitchkit] iterateCodexPages: onRepeatedCursor must be "throw" or "stop", received ${JSON.stringify(onRepeatedCursor)}`);
|
|
2612
|
+
}
|
|
2613
|
+
const signal = options.signal;
|
|
2614
|
+
const seen = new Set;
|
|
2615
|
+
let cursor;
|
|
2616
|
+
for (let pageIndex = 0;pageIndex < options.maxPages; pageIndex += 1) {
|
|
2617
|
+
if (signal?.aborted)
|
|
2618
|
+
throw abortReason(signal);
|
|
2619
|
+
const pending = fetchPage(cursor);
|
|
2620
|
+
const page = signal !== undefined ? await raceAbort(pending, signal) : await pending;
|
|
2621
|
+
if (signal?.aborted)
|
|
2622
|
+
throw abortReason(signal);
|
|
2623
|
+
if (onPage(page) === "stop") {
|
|
2624
|
+
return { truncated: false, stoppedByConsumer: true };
|
|
2577
2625
|
}
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
if (
|
|
2584
|
-
return {
|
|
2585
|
-
kind: "unhandled",
|
|
2586
|
-
delta: {
|
|
2587
|
-
type: "error",
|
|
2588
|
-
...base,
|
|
2589
|
-
itemId: `unhandled:${item.id}`,
|
|
2590
|
-
raw: raw(`${method}/${item.type}`),
|
|
2591
|
-
kind: "unhandled",
|
|
2592
|
-
message: `Codex item ${item.type} is not known to this driver`
|
|
2593
|
-
}
|
|
2594
|
-
};
|
|
2595
|
-
}
|
|
2596
|
-
if (method === "item/started") {
|
|
2597
|
-
return {
|
|
2598
|
-
kind: "deltas",
|
|
2599
|
-
deltas: [
|
|
2600
|
-
{
|
|
2601
|
-
type: "tool-call",
|
|
2602
|
-
...base,
|
|
2603
|
-
itemId: `call:${item.id}`,
|
|
2604
|
-
raw: raw(method),
|
|
2605
|
-
callId: item.id,
|
|
2606
|
-
toolName: toolName(item),
|
|
2607
|
-
input: toolInput(item)
|
|
2608
|
-
}
|
|
2609
|
-
]
|
|
2610
|
-
};
|
|
2626
|
+
const next = page.nextCursor;
|
|
2627
|
+
if (next === null || next === undefined) {
|
|
2628
|
+
return { truncated: false, stoppedByConsumer: false };
|
|
2629
|
+
}
|
|
2630
|
+
if (seen.has(next)) {
|
|
2631
|
+
if (onRepeatedCursor === "stop") {
|
|
2632
|
+
return { truncated: true, stoppedByConsumer: false };
|
|
2611
2633
|
}
|
|
2612
|
-
|
|
2613
|
-
const failure = Reflect.get(item, "failure");
|
|
2614
|
-
const output = failure ?? Reflect.get(item, "aggregatedOutput") ?? Reflect.get(item, "output") ?? Reflect.get(item, "savedPath") ?? Reflect.get(item, "fileId") ?? Reflect.get(item, "result") ?? Reflect.get(item, "results") ?? Reflect.get(item, "contentItems") ?? Reflect.get(item, "changes") ?? Reflect.get(item, "agentsStates") ?? Reflect.get(item, "error");
|
|
2615
|
-
const hasFailure = failure !== undefined && failure !== null;
|
|
2616
|
-
const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
|
|
2617
|
-
return {
|
|
2618
|
-
kind: "deltas",
|
|
2619
|
-
deltas: [
|
|
2620
|
-
{
|
|
2621
|
-
type: "tool-result",
|
|
2622
|
-
...base,
|
|
2623
|
-
itemId: `result:${item.id}`,
|
|
2624
|
-
raw: raw(method),
|
|
2625
|
-
callId: item.id,
|
|
2626
|
-
toolName: toolName(item),
|
|
2627
|
-
outcome,
|
|
2628
|
-
...output !== undefined && output !== null && {
|
|
2629
|
-
output: safeJsonValue(output)
|
|
2630
|
-
}
|
|
2631
|
-
}
|
|
2632
|
-
]
|
|
2633
|
-
};
|
|
2634
|
+
throw new Error(`Codex ${repeatedCursorLabel} repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
2634
2635
|
}
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2636
|
+
seen.add(next);
|
|
2637
|
+
cursor = next;
|
|
2638
|
+
}
|
|
2639
|
+
return { truncated: true, stoppedByConsumer: false };
|
|
2640
|
+
}
|
|
2641
|
+
async function iterateCodexPages(fetchPage, options) {
|
|
2642
|
+
const pages = [];
|
|
2643
|
+
const outcome = await walkCodexPages(fetchPage, options, (page) => {
|
|
2644
|
+
pages.push(page);
|
|
2645
|
+
return "continue";
|
|
2646
|
+
}, "pagination");
|
|
2647
|
+
return { pages, truncated: outcome.truncated };
|
|
2648
|
+
}
|
|
2649
|
+
async function findCodexTurnByClientId(controls, params) {
|
|
2650
|
+
const caller = "findCodexTurnByClientId";
|
|
2651
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
2652
|
+
const clientId = assertRequiredNonEmptyString(params.clientId, "clientId", caller);
|
|
2653
|
+
const maxPages = params.maxPages ?? DEFAULT_FIND_TURN_MAX_PAGES;
|
|
2654
|
+
const pageSize = params.pageSize ?? DEFAULT_FIND_TURN_PAGE_SIZE;
|
|
2655
|
+
assertPositiveSafeInteger(`[stitchkit] ${caller}: maxPages`, maxPages);
|
|
2656
|
+
assertPositiveSafeInteger(`[stitchkit] ${caller}: pageSize`, pageSize);
|
|
2657
|
+
if (pageSize > MAX_UINT322) {
|
|
2658
|
+
throw new TypeError(`[stitchkit] ${caller}: pageSize must not exceed ${MAX_UINT322}`);
|
|
2659
|
+
}
|
|
2660
|
+
if (params.timeoutMs !== undefined) {
|
|
2661
|
+
assertTimerMs("timeoutMs", params.timeoutMs);
|
|
2662
|
+
}
|
|
2663
|
+
const rpcOptions = params.timeoutMs !== undefined || params.signal !== undefined ? {
|
|
2664
|
+
...params.timeoutMs !== undefined && { timeoutMs: params.timeoutMs },
|
|
2665
|
+
...params.signal !== undefined && { signal: params.signal }
|
|
2666
|
+
} : undefined;
|
|
2667
|
+
let matched = null;
|
|
2668
|
+
const outcome = await walkCodexPages((cursor) => controls.listTurns({
|
|
2669
|
+
threadId,
|
|
2670
|
+
limit: pageSize,
|
|
2671
|
+
itemsView: "full",
|
|
2672
|
+
...cursor !== undefined && { cursor }
|
|
2673
|
+
}, rpcOptions), {
|
|
2674
|
+
maxPages,
|
|
2675
|
+
signal: params.signal,
|
|
2676
|
+
onRepeatedCursor: "throw"
|
|
2677
|
+
}, (page) => {
|
|
2678
|
+
for (const turn of page.data) {
|
|
2679
|
+
if (turn.itemsView !== undefined && turn.itemsView !== "full") {
|
|
2680
|
+
throw new Error(`Codex thread/turns/list returned incomplete itemsView ${JSON.stringify(turn.itemsView)} for turn ${turn.id}`);
|
|
2648
2681
|
}
|
|
2649
|
-
deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
|
|
2650
|
-
return { kind: "end", deltas, outcome };
|
|
2651
2682
|
}
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
requestId: String(CodexNotificationParams[method].parse(params).requestId)
|
|
2658
|
-
};
|
|
2659
|
-
case "account/rateLimits/updated": {
|
|
2660
|
-
const parsed = CodexNotificationParams[method].parse(params);
|
|
2661
|
-
return {
|
|
2662
|
-
kind: "limits",
|
|
2663
|
-
rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
|
|
2664
|
-
rateLimits: parsed.rateLimits,
|
|
2665
|
-
rateLimitsByLimitId: parsed.rateLimitsByLimitId
|
|
2666
|
-
} : parsed.rateLimits
|
|
2667
|
-
};
|
|
2683
|
+
for (const turn of page.data) {
|
|
2684
|
+
if (turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId)) {
|
|
2685
|
+
matched = turn;
|
|
2686
|
+
return "stop";
|
|
2687
|
+
}
|
|
2668
2688
|
}
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
type: "error",
|
|
2676
|
-
...base,
|
|
2677
|
-
itemId: `unhandled:${method}`,
|
|
2678
|
-
raw: raw(method),
|
|
2679
|
-
kind: "unhandled",
|
|
2680
|
-
message: `Codex notification ${method} is not known to this driver`
|
|
2681
|
-
}
|
|
2682
|
-
};
|
|
2689
|
+
return "continue";
|
|
2690
|
+
}, "thread/turns/list");
|
|
2691
|
+
if (outcome.stoppedByConsumer)
|
|
2692
|
+
return matched;
|
|
2693
|
+
if (outcome.truncated) {
|
|
2694
|
+
throw new Error(`Codex thread/turns/list exceeded ${maxPages} pages without reaching the end of history`);
|
|
2683
2695
|
}
|
|
2696
|
+
return null;
|
|
2684
2697
|
}
|
|
2685
2698
|
|
|
2686
2699
|
// src/agent-executor/codex/handlers.ts
|
|
@@ -2692,9 +2705,9 @@ function emitCodexNotification(state, method, params, duringActiveTurn, deltas)
|
|
|
2692
2705
|
invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
|
|
2693
2706
|
}
|
|
2694
2707
|
function handleCodexNotification(state, method, params) {
|
|
2695
|
-
const turn = state.getTurn();
|
|
2708
|
+
const turn = codexEventTurn(state.getTurn(), params);
|
|
2696
2709
|
const duringActiveTurn = turn !== undefined;
|
|
2697
|
-
const effectiveTurnId = turn?.state.turnId ??
|
|
2710
|
+
const effectiveTurnId = turn?.state.turnId ?? codexTurnIdOf(params) ?? "external";
|
|
2698
2711
|
let verdict;
|
|
2699
2712
|
try {
|
|
2700
2713
|
verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: effectiveTurnId, interruptRequested: false });
|
|
@@ -2715,9 +2728,11 @@ function handleCodexNotification(state, method, params) {
|
|
|
2715
2728
|
switch (verdict.kind) {
|
|
2716
2729
|
case "limits":
|
|
2717
2730
|
try {
|
|
2731
|
+
const parsedLimits = codexPlanLimits(verdict.rateLimits, new Date);
|
|
2718
2732
|
state.limits.set(state.profileId, mergeRateLimitEvent2({
|
|
2719
2733
|
previous: state.limits.get(state.profileId),
|
|
2720
|
-
windows:
|
|
2734
|
+
windows: parsedLimits.windows,
|
|
2735
|
+
...parsedLimits.plan !== undefined && { plan: parsedLimits.plan },
|
|
2721
2736
|
now: new Date
|
|
2722
2737
|
}));
|
|
2723
2738
|
emitCodexNotification(state, method, params, duringActiveTurn, []);
|
|
@@ -2738,7 +2753,9 @@ function handleCodexNotification(state, method, params) {
|
|
|
2738
2753
|
case "resolved": {
|
|
2739
2754
|
const resolvedTurn = turn?.pending.delete(verdict.requestId) === true;
|
|
2740
2755
|
const externalEntry = state.externalPending.get(verdict.requestId);
|
|
2741
|
-
const
|
|
2756
|
+
const threadId = codexThreadIdOf(params);
|
|
2757
|
+
const nativeTurnId = codexTurnIdOf(params);
|
|
2758
|
+
const resolvedExternal = !resolvedTurn && externalEntry !== undefined && (threadId === undefined || externalEntry.threadId === undefined || threadId === externalEntry.threadId) && (nativeTurnId === undefined || nativeTurnId === externalEntry.turnId);
|
|
2742
2759
|
if (resolvedExternal)
|
|
2743
2760
|
state.externalPending.delete(verdict.requestId);
|
|
2744
2761
|
const resolvedDelta = {
|
|
@@ -2750,7 +2767,7 @@ function handleCodexNotification(state, method, params) {
|
|
|
2750
2767
|
};
|
|
2751
2768
|
if (resolvedTurn && turn !== undefined)
|
|
2752
2769
|
offerTurnDelta(turn.channel, resolvedDelta);
|
|
2753
|
-
emitCodexNotification(state, method, params, duringActiveTurn, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
|
|
2770
|
+
emitCodexNotification(state, method, params, duringActiveTurn && !resolvedExternal, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
|
|
2754
2771
|
return;
|
|
2755
2772
|
}
|
|
2756
2773
|
case "deltas":
|
|
@@ -2765,7 +2782,8 @@ function handleCodexNotification(state, method, params) {
|
|
|
2765
2782
|
}
|
|
2766
2783
|
case "end":
|
|
2767
2784
|
endEngineTurn(turn, codexStopped, verdict.deltas);
|
|
2768
|
-
|
|
2785
|
+
if (turn !== undefined)
|
|
2786
|
+
state.clearTurn();
|
|
2769
2787
|
emitCodexNotification(state, method, params, duringActiveTurn, verdict.deltas);
|
|
2770
2788
|
return;
|
|
2771
2789
|
case "ignore":
|
|
@@ -2774,7 +2792,7 @@ function handleCodexNotification(state, method, params) {
|
|
|
2774
2792
|
}
|
|
2775
2793
|
}
|
|
2776
2794
|
function handleCodexRequest(state, method, params, id) {
|
|
2777
|
-
const turn = state.getTurn();
|
|
2795
|
+
const turn = codexEventTurn(state.getTurn(), params);
|
|
2778
2796
|
if (!isKnownCodexRequestMethod(method)) {
|
|
2779
2797
|
if (turn !== undefined) {
|
|
2780
2798
|
offerTurnDelta(turn.channel, {
|
|
@@ -2837,7 +2855,7 @@ function handleCodexRequest(state, method, params, id) {
|
|
|
2837
2855
|
throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
|
|
2838
2856
|
}
|
|
2839
2857
|
const parsed = parseCodexServerRequest(method, params);
|
|
2840
|
-
const turnId =
|
|
2858
|
+
const turnId = codexTurnIdOf(params) ?? "external";
|
|
2841
2859
|
const delta = {
|
|
2842
2860
|
type: "request",
|
|
2843
2861
|
turnId,
|
|
@@ -2848,7 +2866,13 @@ function handleCodexRequest(state, method, params, id) {
|
|
|
2848
2866
|
...parsed.deltaFields
|
|
2849
2867
|
};
|
|
2850
2868
|
return new Promise((resolve, reject) => {
|
|
2851
|
-
const
|
|
2869
|
+
const threadId = codexThreadIdOf(params);
|
|
2870
|
+
const entry = {
|
|
2871
|
+
detail: parsed.detail,
|
|
2872
|
+
turnId,
|
|
2873
|
+
...threadId !== undefined && { threadId },
|
|
2874
|
+
resolve
|
|
2875
|
+
};
|
|
2852
2876
|
state.externalPending.set(interactionId, entry);
|
|
2853
2877
|
const onObserverError = (error) => {
|
|
2854
2878
|
if (state.externalPending.get(interactionId) !== entry)
|
|
@@ -2885,8 +2909,109 @@ function handleCodexRequest(state, method, params, id) {
|
|
|
2885
2909
|
}
|
|
2886
2910
|
function createCodexHandlers(state) {
|
|
2887
2911
|
return {
|
|
2888
|
-
onNotification
|
|
2889
|
-
|
|
2912
|
+
onNotification(method, params) {
|
|
2913
|
+
const starting = codexEventTurn(state.getTurn(), params)?.starting;
|
|
2914
|
+
const deliver = () => handleCodexNotification(state, method, params);
|
|
2915
|
+
if (starting === undefined)
|
|
2916
|
+
deliver();
|
|
2917
|
+
else
|
|
2918
|
+
starting.defer(params, deliver);
|
|
2919
|
+
},
|
|
2920
|
+
onRequest(method, params, id) {
|
|
2921
|
+
const starting = codexEventTurn(state.getTurn(), params)?.starting;
|
|
2922
|
+
const deliver = () => handleCodexRequest(state, method, params, id);
|
|
2923
|
+
if (starting === undefined)
|
|
2924
|
+
return deliver();
|
|
2925
|
+
return new Promise((resolve, reject) => {
|
|
2926
|
+
starting.defer(params, () => {
|
|
2927
|
+
try {
|
|
2928
|
+
resolve(deliver());
|
|
2929
|
+
} catch (error) {
|
|
2930
|
+
reject(error);
|
|
2931
|
+
}
|
|
2932
|
+
});
|
|
2933
|
+
});
|
|
2934
|
+
}
|
|
2935
|
+
};
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
// src/agent-executor/codex/session-bind.ts
|
|
2939
|
+
function bindCodexSessionThreadControls(controlClient, threadId) {
|
|
2940
|
+
return {
|
|
2941
|
+
readThread(params, options) {
|
|
2942
|
+
return controlClient.readThread({
|
|
2943
|
+
...params,
|
|
2944
|
+
threadId: params?.threadId ?? threadId
|
|
2945
|
+
}, options);
|
|
2946
|
+
},
|
|
2947
|
+
listTurns(params, options) {
|
|
2948
|
+
return controlClient.listTurns({
|
|
2949
|
+
...params,
|
|
2950
|
+
threadId: params?.threadId ?? threadId
|
|
2951
|
+
}, options);
|
|
2952
|
+
},
|
|
2953
|
+
listItems(params, options) {
|
|
2954
|
+
return controlClient.listItems({
|
|
2955
|
+
...params,
|
|
2956
|
+
threadId: params?.threadId ?? threadId
|
|
2957
|
+
}, options);
|
|
2958
|
+
},
|
|
2959
|
+
resumeThread(params, options) {
|
|
2960
|
+
return controlClient.resumeThread({
|
|
2961
|
+
...params,
|
|
2962
|
+
threadId: params?.threadId ?? threadId
|
|
2963
|
+
}, options);
|
|
2964
|
+
},
|
|
2965
|
+
revertThread(params, options) {
|
|
2966
|
+
return controlClient.revertThread({
|
|
2967
|
+
...params,
|
|
2968
|
+
threadId: params.threadId ?? threadId
|
|
2969
|
+
}, options);
|
|
2970
|
+
},
|
|
2971
|
+
injectItems(params, options) {
|
|
2972
|
+
return controlClient.injectItems({
|
|
2973
|
+
...params,
|
|
2974
|
+
threadId: params.threadId ?? threadId
|
|
2975
|
+
}, options);
|
|
2976
|
+
},
|
|
2977
|
+
unsubscribeThread(params, options) {
|
|
2978
|
+
return controlClient.unsubscribeThread({
|
|
2979
|
+
threadId: params?.threadId ?? threadId
|
|
2980
|
+
}, options);
|
|
2981
|
+
},
|
|
2982
|
+
archiveThread(params, options) {
|
|
2983
|
+
return controlClient.archiveThread({
|
|
2984
|
+
threadId: params?.threadId ?? threadId
|
|
2985
|
+
}, options);
|
|
2986
|
+
},
|
|
2987
|
+
unarchiveThread(params, options) {
|
|
2988
|
+
return controlClient.unarchiveThread({
|
|
2989
|
+
threadId: params?.threadId ?? threadId
|
|
2990
|
+
}, options);
|
|
2991
|
+
},
|
|
2992
|
+
updateThreadMetadata(params, options) {
|
|
2993
|
+
return controlClient.updateThreadMetadata({
|
|
2994
|
+
...params,
|
|
2995
|
+
threadId: params?.threadId ?? threadId
|
|
2996
|
+
}, options);
|
|
2997
|
+
},
|
|
2998
|
+
setThreadName(params, options) {
|
|
2999
|
+
return controlClient.setThreadName({
|
|
3000
|
+
...params,
|
|
3001
|
+
threadId: params.threadId ?? threadId
|
|
3002
|
+
}, options);
|
|
3003
|
+
},
|
|
3004
|
+
interruptTurn(params, options) {
|
|
3005
|
+
return controlClient.interruptTurn({
|
|
3006
|
+
...params,
|
|
3007
|
+
threadId: params.threadId ?? threadId
|
|
3008
|
+
}, options);
|
|
3009
|
+
},
|
|
3010
|
+
compactThread(params, options) {
|
|
3011
|
+
return controlClient.compactThread({
|
|
3012
|
+
threadId: params?.threadId ?? threadId
|
|
3013
|
+
}, options);
|
|
3014
|
+
}
|
|
2890
3015
|
};
|
|
2891
3016
|
}
|
|
2892
3017
|
|
|
@@ -2976,7 +3101,8 @@ async function openCodexSession(config, input) {
|
|
|
2976
3101
|
linked.signal.throwIfAborted();
|
|
2977
3102
|
}
|
|
2978
3103
|
const openedReply = await openCodexThreadRpc(peer, config, input, dynamicOverrides);
|
|
2979
|
-
const
|
|
3104
|
+
const openMethod = input.forkFrom !== undefined ? "thread/fork" : input.nativeThreadId !== undefined ? "thread/resume" : "thread/start";
|
|
3105
|
+
const parsed = parseCodexResponse(openMethod, CodexStartedThreadSchema, openedReply);
|
|
2980
3106
|
threadId = parsed.thread.id;
|
|
2981
3107
|
activeThreadId = threadId;
|
|
2982
3108
|
threadContext = extractCodexThreadContext(parsed);
|
|
@@ -3279,7 +3405,8 @@ async function openSharedCodexThread(state, threadInput) {
|
|
|
3279
3405
|
const openedReply = await raceAbort(openCodexThreadRpc(state.peer, state.config, threadInput, dynamicOverrides), threadAbort.signal, disposeLateOpen);
|
|
3280
3406
|
threadAbort.signal.throwIfAborted();
|
|
3281
3407
|
state.ensureServerAlive();
|
|
3282
|
-
const
|
|
3408
|
+
const openMethod = threadInput.forkFrom !== undefined ? "thread/fork" : threadInput.nativeThreadId !== undefined ? "thread/resume" : "thread/start";
|
|
3409
|
+
const parsed = parseCodexResponse(openMethod, CodexStartedThreadSchema, openedReply);
|
|
3283
3410
|
const threadId = parsed.thread.id;
|
|
3284
3411
|
const threadContext = extractCodexThreadContext(parsed);
|
|
3285
3412
|
if (state.threads.has(threadId)) {
|
|
@@ -3355,19 +3482,6 @@ async function openSharedCodexThread(state, threadInput) {
|
|
|
3355
3482
|
// src/agent-executor/codex/shared-server.ts
|
|
3356
3483
|
var DEFAULT_MAX_SHARED_THREADS = 32;
|
|
3357
3484
|
var HARD_MAX_SHARED_THREADS = 256;
|
|
3358
|
-
function extractCodexThreadId(params) {
|
|
3359
|
-
if (!isRecord(params))
|
|
3360
|
-
return;
|
|
3361
|
-
if (typeof params.threadId === "string" && params.threadId.length > 0)
|
|
3362
|
-
return params.threadId;
|
|
3363
|
-
if (isRecord(params.thread) && typeof params.thread.id === "string" && params.thread.id.length > 0) {
|
|
3364
|
-
return params.thread.id;
|
|
3365
|
-
}
|
|
3366
|
-
if (isRecord(params.turn) && typeof params.turn.threadId === "string" && params.turn.threadId.length > 0) {
|
|
3367
|
-
return params.turn.threadId;
|
|
3368
|
-
}
|
|
3369
|
-
return;
|
|
3370
|
-
}
|
|
3371
3485
|
function validateSharedServerInputs(config, input) {
|
|
3372
3486
|
if (config.transport !== undefined && config.transport.kind !== "stdio") {
|
|
3373
3487
|
throw new TypeError(`[stitchkit] CodexDriver.openSharedServer: shared multi-thread mode requires stdio transport (received ${JSON.stringify(config.transport.kind)})`);
|
|
@@ -3425,7 +3539,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3425
3539
|
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3426
3540
|
return;
|
|
3427
3541
|
}
|
|
3428
|
-
const targetId =
|
|
3542
|
+
const targetId = codexThreadIdOf(params);
|
|
3429
3543
|
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3430
3544
|
if (slot !== undefined) {
|
|
3431
3545
|
invokeSafely(() => slot.handlers.onNotification(method, params));
|
|
@@ -3434,7 +3548,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3434
3548
|
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3435
3549
|
},
|
|
3436
3550
|
onRequest(method, params, id) {
|
|
3437
|
-
const targetId =
|
|
3551
|
+
const targetId = codexThreadIdOf(params);
|
|
3438
3552
|
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3439
3553
|
if (slot !== undefined)
|
|
3440
3554
|
return slot.handlers.onRequest(method, params, id);
|
|
@@ -3519,32 +3633,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
|
3519
3633
|
}
|
|
3520
3634
|
|
|
3521
3635
|
// src/agent-executor/codex/driver.ts
|
|
3522
|
-
var MAX_HISTORY_PAGES = 256;
|
|
3523
3636
|
var FIND_INPUT_MAX_LINE_BYTES = 64 * 1024 * 1024;
|
|
3524
|
-
async function findCodexClientInput(peer, nativeThreadId, clientId) {
|
|
3525
|
-
const seen = new Set;
|
|
3526
|
-
let cursor;
|
|
3527
|
-
for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
|
|
3528
|
-
const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
|
|
3529
|
-
threadId: nativeThreadId,
|
|
3530
|
-
limit: 50,
|
|
3531
|
-
itemsView: "full",
|
|
3532
|
-
...cursor !== undefined && { cursor }
|
|
3533
|
-
}));
|
|
3534
|
-
if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId))) {
|
|
3535
|
-
return true;
|
|
3536
|
-
}
|
|
3537
|
-
const next = page.nextCursor;
|
|
3538
|
-
if (next === null || next === undefined)
|
|
3539
|
-
return false;
|
|
3540
|
-
if (seen.has(next)) {
|
|
3541
|
-
throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
3542
|
-
}
|
|
3543
|
-
seen.add(next);
|
|
3544
|
-
cursor = next;
|
|
3545
|
-
}
|
|
3546
|
-
throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
|
|
3547
|
-
}
|
|
3548
3637
|
function validateCodexDriverOptions(config) {
|
|
3549
3638
|
validateImageOptions(config);
|
|
3550
3639
|
assertPositiveSafeInteger("maxFrameBytes", config.maxFrameBytes);
|
|
@@ -3658,37 +3747,68 @@ function createCodexDriver(config = {}) {
|
|
|
3658
3747
|
const decoder = new TextDecoder;
|
|
3659
3748
|
const text = `${decoder.decode(loginResult.stdout)}
|
|
3660
3749
|
${decoder.decode(loginResult.stderr)}`.trim();
|
|
3661
|
-
const
|
|
3662
|
-
const
|
|
3663
|
-
|
|
3750
|
+
const line = text.split(/\r?\n/).map((value) => value.trim()).find((value) => /^Logged in(?:\s|$)/i.test(value));
|
|
3751
|
+
const signedIn = loginResult.exitCode === 0 && line !== undefined;
|
|
3752
|
+
const signedOut = loginResult.exitCode === 1 && /^Not logged in\s*$/im.test(text);
|
|
3753
|
+
const credential = signedIn ? /chatgpt/i.test(line) ? "subscription" : /api key/i.test(line) ? "api-key" : "unknown" : signedOut ? "none" : "unknown";
|
|
3754
|
+
let planLimits;
|
|
3664
3755
|
if (credential === "subscription") {
|
|
3665
3756
|
try {
|
|
3666
3757
|
const answer = await ask(parsed, process.cwd(), (peer) => peer.request("account/rateLimits/read"));
|
|
3667
|
-
const
|
|
3668
|
-
planLimits =
|
|
3758
|
+
const snapshot = codexPlanLimits(answer);
|
|
3759
|
+
planLimits = {
|
|
3760
|
+
...snapshot,
|
|
3761
|
+
windows: snapshot.windows.toSorted((a, b) => a.name.localeCompare(b.name))
|
|
3762
|
+
};
|
|
3669
3763
|
limits.set(parsed.profileId, planLimits);
|
|
3670
3764
|
} catch (error) {
|
|
3671
3765
|
planLimits = planLimitsReadFailed2({
|
|
3672
|
-
previous:
|
|
3766
|
+
previous: limits.get(parsed.profileId),
|
|
3673
3767
|
error: error instanceof Error ? error.message : String(error),
|
|
3674
3768
|
now: new Date
|
|
3675
3769
|
});
|
|
3676
3770
|
}
|
|
3677
3771
|
} else if (credential === "api-key") {
|
|
3772
|
+
limits.delete(parsed.profileId);
|
|
3678
3773
|
planLimits = {
|
|
3679
3774
|
answer: "no-plan-limit",
|
|
3680
3775
|
windows: [],
|
|
3681
3776
|
observedAt: new Date().toISOString()
|
|
3682
3777
|
};
|
|
3683
3778
|
}
|
|
3779
|
+
if (signedOut)
|
|
3780
|
+
limits.delete(parsed.profileId);
|
|
3781
|
+
if (credential === "unknown") {
|
|
3782
|
+
const previous = limits.get(parsed.profileId);
|
|
3783
|
+
if (previous !== undefined)
|
|
3784
|
+
planLimits = planLimitsReadFailed2({
|
|
3785
|
+
previous,
|
|
3786
|
+
error: "Codex login status could not confirm the credential",
|
|
3787
|
+
now: new Date
|
|
3788
|
+
});
|
|
3789
|
+
}
|
|
3684
3790
|
return {
|
|
3685
|
-
login: { state: signedIn ? "signed-in" : "signed-out" },
|
|
3791
|
+
login: { state: signedIn ? "signed-in" : signedOut ? "signed-out" : "unknown" },
|
|
3686
3792
|
effectiveCredential: credential,
|
|
3687
3793
|
...planLimits && { planLimits }
|
|
3688
3794
|
};
|
|
3689
3795
|
},
|
|
3690
3796
|
async findInput(input) {
|
|
3691
|
-
return ask(input.profile, input.cwd, (peer) =>
|
|
3797
|
+
return ask(input.profile, input.cwd, async (peer) => {
|
|
3798
|
+
const controls = createCodexControlClient({
|
|
3799
|
+
peer,
|
|
3800
|
+
imageOptions: config,
|
|
3801
|
+
signal: new AbortController().signal,
|
|
3802
|
+
ensureAlive: () => {
|
|
3803
|
+
return;
|
|
3804
|
+
}
|
|
3805
|
+
});
|
|
3806
|
+
const found = await findCodexTurnByClientId(controls, {
|
|
3807
|
+
threadId: input.nativeThreadId,
|
|
3808
|
+
clientId: input.clientId
|
|
3809
|
+
});
|
|
3810
|
+
return found !== null;
|
|
3811
|
+
}, Math.max(FIND_INPUT_MAX_LINE_BYTES, config.maxFrameBytes ?? 0));
|
|
3692
3812
|
},
|
|
3693
3813
|
open: (input) => openCodexSession(session(), input),
|
|
3694
3814
|
connectControl: (input) => openCodexControlConnection(session(), input),
|
|
@@ -3781,10 +3901,55 @@ var codexFakeScenarios = {
|
|
|
3781
3901
|
crash: () => steps(text("dying "), { do: "crash" })
|
|
3782
3902
|
};
|
|
3783
3903
|
export {
|
|
3904
|
+
CODEX_THREAD_SOURCE_KINDS2 as CODEX_THREAD_SOURCE_KINDS,
|
|
3905
|
+
CODEX_TOOL_ITEMS,
|
|
3906
|
+
CodexAccountReadResponseSchema,
|
|
3907
|
+
CodexAccountSchema,
|
|
3908
|
+
CodexApprovalPolicySchema2 as CodexApprovalPolicySchema,
|
|
3909
|
+
CodexCollaborationModePresetSchema,
|
|
3910
|
+
CodexCollaborationModeSchema2 as CodexCollaborationModeSchema,
|
|
3911
|
+
CodexCollaborationModesResponseSchema,
|
|
3912
|
+
CodexConfigReadResponseSchema,
|
|
3913
|
+
CodexConfigSchema,
|
|
3914
|
+
CodexItemsPageSchema,
|
|
3915
|
+
CodexListedTurnSchema2 as CodexListedTurnSchema,
|
|
3916
|
+
CodexLoadedThreadsPageSchema,
|
|
3784
3917
|
CodexLocalImageInputSchema,
|
|
3918
|
+
CodexMcpServerStatusPageSchema,
|
|
3919
|
+
CodexMcpServerStatusSchema,
|
|
3920
|
+
CodexModelSchema,
|
|
3921
|
+
CodexModelsPageSchema,
|
|
3922
|
+
CodexNotificationParams,
|
|
3923
|
+
CodexProtocolError2 as CodexProtocolError,
|
|
3924
|
+
CodexRateLimitSnapshotSchema,
|
|
3925
|
+
CodexRateLimitWindowSchema,
|
|
3926
|
+
CodexRateLimitsResponseSchema,
|
|
3927
|
+
CodexReadThreadResponseSchema,
|
|
3928
|
+
CodexResumeThreadResponseSchema,
|
|
3929
|
+
CodexSandboxModeSchema2 as CodexSandboxModeSchema,
|
|
3930
|
+
CodexSandboxPolicySchema2 as CodexSandboxPolicySchema,
|
|
3785
3931
|
CodexSkillInputSchema,
|
|
3786
|
-
|
|
3932
|
+
CodexSkillsListResponseSchema,
|
|
3933
|
+
CodexThreadContextSchema2 as CodexThreadContextSchema,
|
|
3934
|
+
CodexThreadItemEntrySchema,
|
|
3935
|
+
CodexThreadItemSchema2 as CodexThreadItemSchema,
|
|
3936
|
+
CodexThreadMetadataUpdateResponseSchema,
|
|
3937
|
+
CodexThreadSchema2 as CodexThreadSchema,
|
|
3938
|
+
CodexThreadSourceKindSchema2 as CodexThreadSourceKindSchema,
|
|
3939
|
+
CodexThreadStatusSchema2 as CodexThreadStatusSchema,
|
|
3940
|
+
CodexThreadUnarchiveResponseSchema,
|
|
3941
|
+
CodexThreadUnsubscribeResponseSchema,
|
|
3942
|
+
CodexThreadUnsubscribeStatusSchema,
|
|
3943
|
+
CodexThreadsPageSchema,
|
|
3944
|
+
CodexTurnItemsViewSchema2 as CodexTurnItemsViewSchema,
|
|
3945
|
+
CodexTurnStatusSchema2 as CodexTurnStatusSchema,
|
|
3946
|
+
CodexTurnsPageSchema2 as CodexTurnsPageSchema,
|
|
3947
|
+
CodexUnixSocketError2 as CodexUnixSocketError,
|
|
3787
3948
|
codexFakeScenarios,
|
|
3949
|
+
codexPlanLimits,
|
|
3788
3950
|
codexPlanWindows,
|
|
3789
|
-
createCodexDriver
|
|
3951
|
+
createCodexDriver,
|
|
3952
|
+
findCodexTurnByClientId,
|
|
3953
|
+
iterateCodexPages,
|
|
3954
|
+
parseCodexNotification
|
|
3790
3955
|
};
|